@FahadM to JavaScriptEnglish • 5 days ago

How do you strip or remove a specific substring from a JavaScript string?

message-square
0
1
How do you strip or remove a specific substring from a JavaScript string?
@FahadM to JavaScriptEnglish • 5 days ago

To strip or remove a specific literal substring from a JavaScript string without mutating the original string (strings are immutable in JavaScript), use str.replaceAll(target, "") to remove every occurrence, or str.replace(target, "") to remove only the first occurrence. For prefix/suffix trimming when a substring sits strictly at the start or end, str.startsWith() / str.endsWith() with .slice() (or .replace() anchored with ^ / $) is even more exact.


1. Removing All or First Occurrences with .replaceAll() and .replace()

Pass the exact substring and an empty string "" to .replaceAll() or .replace()—both return a new string and leave the input untouched:

// Strip all or only the first occurrence of a literal substring
function removeSubstring(source, target, { all = true } = {}) {
  if (typeof source !== "string" || typeof target !== "string" || target === "") {
    return source;
  }

  return all ? source.replaceAll(target, "") : source.replace(target, "");
}

const rawSlug = "v1/users/v1/profile/v1";
console.log("Remove all 'v1':", removeSubstring(rawSlug, "v1", { all: true }));   // "/users//profile/"
console.log("Remove first 'v1':", removeSubstring(rawSlug, "v1", { all: false })); // "/users/v1/profile/v1"
  • String.prototype.replaceAll(target, ""): Removes every literal match of target without needing regex escaping (supported in ES2021+ and all modern Node.js/browser runtimes).
  • String.prototype.replace(target, ""): Removes only the first literal match when target is a string.
  • Empty target guard: Calling "".replaceAll("", "") or str.replaceAll("", "") inserts/removes around every character boundary in unexpected ways, so guard target === "".

2. Stripping Leading Prefixes or Trailing Suffixes Safely

When removing a substring only from the start (such as "Bearer " or "https://") or end (such as ".json" or "/"), check the boundary explicitly so you do not strip a matching substring that appears later in the middle of the string:

// Strip a leading prefix or trailing suffix only at the exact boundary
function stripPrefix(value, prefix) {
  if (typeof value !== "string" || typeof prefix !== "string" || prefix === "") {
    return value;
  }

  return value.startsWith(prefix) ? value.slice(prefix.length) : value;
}

function stripSuffix(value, suffix) {
  if (typeof value !== "string" || typeof suffix !== "string" || suffix === "") {
    return value;
  }

  return value.endsWith(suffix) ? value.slice(0, -suffix.length) : value;
}

const authHeader = "Bearer eyJhbGciOiJIUzI1NiJ9.token";
const endpointPath = "/api/reports.json";

console.log("Token without prefix:", stripPrefix(authHeader, "Bearer ")); // "eyJhbGciOiJIUzI1NiJ9.token"
console.log("Path without .json:", stripSuffix(endpointPath, ".json"));    // "/api/reports"
  • startsWith() + .slice(prefix.length): Only removes prefix at index 0, leaving identical text inside tokens or URLs intact.
  • endsWith() + .slice(0, -suffix.length): Only removes suffix at the very end of the string.

3. Common Traps to Avoid

Stripping substrings in JavaScript often runs into a few subtle pitfalls:

  • Using str.replace(substring, "") expecting all matches to be removed: A string argument in .replace() replaces only the first occurrence—use .replaceAll(substring, "") to remove all occurrences.
  • Passing unescaped user/dynamic strings into new RegExp(target, "g"): Characters like ., *, +, ?, (, ), [, ], {, }, ^, $, |, and \ have special regex meaning—prefer .replaceAll(literalString, "") for literal substrings so dots or brackets do not match unintended characters.
  • Expecting string removal to mutate in place: JavaScript strings are immutable; if you ignore the return value (text.replaceAll("foo", "") without reassigning), text remains unchanged.

TL;DR: Use str.replaceAll(sub, "") to remove all literal occurrences, str.replace(sub, "") for the first occurrence, or startsWith()/endsWith() + .slice() to strip exact prefixes or suffixes safely.

Are you removing all occurrences of a literal substring, stripping a prefix/suffix like "Bearer " or a file extension, or cleaning up extra spaces/delimiters left behind after removal?