To remove whitespace from strings in JavaScript, use str.trim() to remove leading and trailing whitespace, str.trimStart() (or legacy trimLeft()) to remove only leading whitespace, str.trimEnd() (or legacy trimRight()) to remove only trailing whitespace, and str.replace(/\s+/g, "") (or replaceAll(...)) when you want to remove all internal whitespace or collapse multiple spaces into a single space using .replace(/\s+/g, " ").trim(). Because JavaScript strings are immutable, every one of these methods returns a new string without modifying the original value.


1. Trimming Leading and Trailing Whitespace (trim(), trimStart(), trimEnd())

Use trim(), trimStart(), and trimEnd() to strip whitespace characters (spaces, tabs, and line breaks) from the edges of a string:

// Remove leading, trailing, or edge-specific whitespace from a string
function trimEdges(input, { leading = true, trailing = true } = {}) {
  if (typeof input !== "string") {
    throw new TypeError("Expected input to be a string.");
  }

  if (leading && trailing) return input.trim();
  if (leading) return input.trimStart();
  if (trailing) return input.trimEnd();
  return input;
}

// Example usage:
const rawLine = "  \t  Hello, JavaScript!  \n ";
console.log(JSON.stringify(rawLine.trim()));      // "\"Hello, JavaScript!\""
console.log(JSON.stringify(rawLine.trimStart())); // "\"Hello, JavaScript!  \\n \""
console.log(JSON.stringify(rawLine.trimEnd()));   // "\"  \\t  Hello, JavaScript!\""
  • Strings are immutable: Calling str.trim() leaves str unchanged and returns a new trimmed string.
  • Covers Unicode whitespace: Built-in trim methods remove spaces, tabs (\t), newlines (\n, \r), and other Unicode whitespace characters.

2. Removing All Whitespace or Collapsing Multiple Spaces

trim() does not touch spaces or line breaks inside a string—use regular expressions with replace() when you need to strip all whitespace or normalize internal spacing:

// Remove all whitespace characters, or collapse runs of whitespace into a single space
function removeAllWhitespace(input) {
  if (typeof input !== "string") {
    throw new TypeError("Expected input to be a string.");
  }

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

function normalizeWhitespace(input) {
  if (typeof input !== "string") {
    throw new TypeError("Expected input to be a string.");
  }

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

// Example usage:
console.log(removeAllWhitespace(" 123 - 456 \n 789 ")); // "123-456789"
console.log(normalizeWhitespace("  Too   many   spaces\t\nhere  ")); // "Too many spaces here"
  • \s matches any whitespace: In regex, \s matches spaces, tabs, carriage returns, and newlines, while + matches one or more consecutive characters.
  • Be careful with text readability: Removing all spaces (/\s+/g) merges words together, so use normalizeWhitespace() when preserving word boundaries matters.

3. Removing Specific Whitespace Types (Spaces vs. Newlines/Tabs)

If you only want to strip line breaks or collapse spaces without affecting other characters, target that specific pattern rather than using a broad replacement:

// Strip newline characters or remove only standard ASCII spaces
function stripNewlines(input) {
  if (typeof input !== "string") {
    throw new TypeError("Expected input to be a string.");
  }

  return input.replace(/[\r\n]+/g, " ").trim();
}

function removeSpacesOnly(input) {
  if (typeof input !== "string") {
    throw new TypeError("Expected input to be a string.");
  }

  return input.replaceAll(" ", "");
}

// Example usage:
console.log(stripNewlines("Line one\r\nLine two\nLine three")); // "Line one Line two Line three"
console.log(removeSpacesOnly("a b\tc")); // "ab\tc" (tab preserved)
  • Targeted vs. broad removal: replaceAll(" ", "") only removes literal space characters (" "), leaving tabs and newlines intact.
  • Guard non-string values: Checking typeof input === "string" prevents TypeError: input.trim is not a function on null, undefined, or numbers.

TL;DR: Use str.trim() (or trimStart() / trimEnd()) for leading/trailing whitespace, str.replace(/\s+/g, "") to remove all whitespace, and str.trim().replace(/\s+/g, " ") to collapse multiple spaces into one.