← Back to all snippets
JAVASCRIPT

Normalize Whitespace and Trim String

Learn to clean up strings by replacing multiple spaces (including tabs and newlines) with a single space and removing leading/trailing whitespace using regular expressions in JavaScript.

function normalizeWhitespace(text) {
  // Replace multiple spaces (or tabs, newlines) with a single space
  let cleanedText = text.replace(/\s+/g, ' ');
  // Remove leading/trailing whitespace
  return cleanedText.trim();
}

// Examples
console.log(normalizeWhitespace("  Hello    World!   ")); // "Hello World!"
console.log(normalizeWhitespace("Line one
  Line two\tLine three")); // "Line one Line two Line three"
console.log(normalizeWhitespace("No extra spaces.")); // "No extra spaces."
How it works: This JavaScript function first uses the `/\s+/g` regex to replace any sequence of one or more whitespace characters (including spaces, tabs, newlines) with a single space. Then, `trim()` removes any remaining leading or trailing whitespace, resulting in a clean, normalized string often required for user input or data processing.

Need help integrating this into your project?

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

Hire DigitalCodeLabs