JAVASCRIPT

Normalize Whitespace: Replace Multiple Spaces

Learn to clean up user input or text content by using a simple JavaScript regex to replace consecutive whitespace characters with a single space.

function normalizeWhitespace(text) {
  // Replaces one or more whitespace characters (including spaces, tabs, newlines)
  // with a single space, then trims leading/trailing spaces.
  return text.replace(/\s+/g, ' ').trim();
}

const messyText = "  Hello   world!  
 This text has   too  much \t whitespace.   ";
console.log("Original text:");
console.log(`"${messyText}"`);
console.log("Normalized text:");
console.log(`"${normalizeWhitespace(messyText)}"`);

const simpleText = "One two   three.";
console.log(`"${normalizeWhitespace(simpleText)}"`);
How it works: This JavaScript function `normalizeWhitespace` takes a string and cleans it by replacing all occurrences of one or more consecutive whitespace characters (including spaces, tabs, and newlines) with a single space. The `\s+` regex matches one or more whitespace characters, and the `g` flag ensures a global replacement. Finally, `trim()` is called to remove any leading or trailing spaces that might result from 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