← Back to all snippets
JAVASCRIPT

Normalize Whitespace to Single Spaces

Clean up strings by replacing sequences of multiple spaces or tabs with a single space using a simple JavaScript regular expression `replace()` method, followed by trimming.

function normalizeSpaces(text) {
  // Replace one or more whitespace characters (space, tab, newline, etc.)
  // with a single space.
  // Use 'g' flag for global replacement.
  // Use ' +' to match one or more spaces, or '\s+' for any whitespace.
  return text.replace(/\s+/g, ' ').trim();
}

const messyText = "  Hello   world!  How are\twe?  ";
const cleanedText = normalizeSpaces(messyText);
console.log(`"${messyText}"`);
console.log(`"${cleanedText}"`); // Output: "Hello world! How are we?"

const anotherMessyText = "  Leading and trailing   spaces.  ";
console.log(`"${normalizeSpaces(anotherMessyText)}"`); // Output: "Leading and trailing spaces."
How it works: The `normalizeSpaces` JavaScript function cleans up text by replacing any sequence of one or more whitespace characters (spaces, tabs, newlines, etc.) with a single space. The regex `/\s+/g` uses `\s` to match any whitespace character and `+` to match one or more occurrences. The `g` flag ensures all occurrences are replaced, not just the first. Finally, `.trim()` is called to remove any leading or trailing spaces that might remain after the replacement.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs