How do you strip all whitespace characters from a string in JavaScript? | A1Lab@FahadM to JavaScriptEnglish • 3 days ago

How do you strip all whitespace characters from a string in JavaScript?

message-square
0

To strip all whitespace characters from a string in JavaScript without mutating the original string, call text.replace(/\s+/g, "") (or text.replace(/[\s\uFEFF\xA0]+/g, "") when you want to be explicit about Unicode spaces, non-breaking spaces \u00A0, and byte-order marks \uFEFF). Unlike String.prototype.trim(), which only removes leading and trailing whitespace, .replace(/\s+/g, "") removes every space, tab (\t), newline (\n, \r), and other whitespace character anywhere in the string and returns a new string.


1. Removing All Whitespace with String.prototype.replace(/\s+/g, "")

Use the global regex /\s+/g with an empty replacement string "" to strip every whitespace sequence across the entire string:

// Non-mutating helper to remove all whitespace characters from a string
function stripAllWhitespace(text) {
  if (typeof text !== "string") {
    throw new TypeError("Expected text to be a string.");
  }

  return text.replace(/\s+/g, "");
}

// Example usage:
const rawCode = "  AB-12\t 34 \r\n CD  ";
console.log(stripAllWhitespace(rawCode)); // "AB-1234CD"
console.log(rawCode);                    // "  AB-12\t 34 \r\n CD  " (unchanged)
  • Strips internal and outer whitespace: Unlike .trim(), .replace(/\s+/g, "") removes spaces and tabs inside the string as well as at the ends.
  • Strings are immutable in JavaScript: .replace() always returns a new string without modifying rawCode.

2. Handling Non-Breaking Spaces (\u00A0), BOM, and Unicode Whitespace

Copied text from web pages, HTML entities (�), or files can include non-breaking spaces (\u00A0), zero-width/BOM characters (\uFEFF), or other Unicode whitespace; combining \s with explicit characters or \p{White_Space} gives thorough coverage:

// Strip standard whitespace plus non-breaking spaces and BOM characters
function stripAllWhitespaceThorough(text) {
  if (typeof text !== "string") {
    throw new TypeError("Expected text to be a string.");
  }

  return text.replace(/[\s\u00A0\uFEFF]+/g, "");
}

// Example usage:
const withNbsp = "100\u00A0\u00A0USD\uFEFF";
console.log(stripAllWhitespaceThorough(withNbsp)); // "100USD"
  • Watch out for \u00A0 (NBSP): HTML non-breaking spaces appear as normal spaces visually and can slip past naive string checks if not handled.
  • Unicode property escape (\p{White_Space}): Modern JS engines support /\p{White_Space}+/gu to match all Unicode whitespace code points.

3. Collapsing Internal Whitespace Instead of Stripping All of It

Often you want to normalize multiple spaces/tabs/newlines into a single space (" ") and trim the ends rather than deleting every space between words:

// Non-mutating helper to collapse runs of whitespace into a single space
function collapseWhitespace(text) {
  if (typeof text !== "string") {
    throw new TypeError("Expected text to be a string.");
  }

  return text.replace(/\s+/g, " ").trim();
}

// Example usage:
const sentence = "  Too   many\n\tspaces   here  ";
console.log(collapseWhitespace(sentence)); // "Too many spaces here"
  • Don’t strip spaces from human text blindly: Removing all spaces turns "Hello world" into "Helloworld"; use .replace(/\s+/g, " ").trim() for readable text and strip-all only for tokens, IDs, or codes.
  • Avoid .replace(" ", "") without /g: A plain string replacement only removes the first single space character.

TL;DR: Use str.replace(/\s+/g, "") (or str.replace(/[\s\u00A0\uFEFF]+/g, "") for NBSP/BOM) to strip all whitespace characters from a string non-mutatingly—and use .replace(/\s+/g, " ").trim() if you only want to collapse extra spaces between words.