← Back to all snippets
JAVASCRIPT

Normalize Whitespace in Strings with Regex

Learn to clean up user input or textual data by compressing multiple spaces into single spaces and trimming leading/trailing whitespace using a simple JavaScript Regex.

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

const messyText = "  This   is a 
 sentence   with   excessive  whitespace.  ";
const cleanText = normalizeWhitespace(messyText);
console.log(cleanText);
// Expected Output: This is a sentence with excessive whitespace.
How it works: This JavaScript function normalizes whitespace in a string. It uses the regex `/\s+/g` to match one or more (`+`) whitespace characters (`\s`, which includes spaces, tabs, newlines). All matched sequences are replaced with a single space. Finally, `trim()` removes any leading or trailing whitespace that might remain.

Need help integrating this into your project?

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

Hire DigitalCodeLabs