← Back to all snippets
JAVASCRIPT

Replace Multiple Spaces with Single Space

Clean up user input or textual data by replacing all sequences of one or more whitespace characters with a single space using regex in JavaScript.

function normalizeSpaces(text) {
    // Replaces one or more whitespace characters (spaces, tabs, newlines, etc.) with a single space.
    // .trim() is added to remove leading/trailing spaces from the result.
    return text.replace(/\s+/g, ' ').trim();
}

const messyText = "  Hello   World!  
  This is a test.   ";
const cleanText = normalizeSpaces(messyText);
console.log(cleanText);
// Expected: "Hello World! This is a test."
How it works: The `normalizeSpaces` function uses the regular expression `/\s+/g` to find all occurrences of one or more whitespace characters (including spaces, tabs, and newlines). It then replaces them with a single space. The `.trim()` method is subsequently used to remove any leading or trailing spaces from the final string, resulting in clean, normalized text.

Need help integrating this into your project?

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

Hire DigitalCodeLabs