JAVASCRIPT

Normalize Whitespace: Replace Multiple Spaces with Single

Discover how to clean up text strings in JavaScript by using a regex to replace any sequence of multiple whitespace characters (spaces, tabs, newlines) with a single space.

function normalizeWhitespace(text) {
  // Replace multiple whitespace characters (including newlines, tabs) with a single space.
  // Then trim leading/trailing whitespace.
  if (typeof text !== 'string') return '';
  return text.replace(/\s+/g, ' ').trim();
}

const messyText = "  Hello   world! 
  This is a   test.  ";
const cleanedText = normalizeWhitespace(messyText); // "Hello world! This is a test."

const singleSpaceText = "Already clean text.";
const cleanedSingle = normalizeWhitespace(singleSpaceText); // "Already clean text."
How it works: The `normalizeWhitespace` function takes a string and uses the regex `/\s+/g` to find one or more whitespace characters (including spaces, tabs, newlines). It replaces all such occurrences with a single space. Finally, `trim()` is called to remove any leading or trailing whitespace that might remain after the replacements, ensuring a perfectly normalized string for display or storage.

Need help integrating this into your project?

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

Hire DigitalCodeLabs