JAVASCRIPT

Standardizing Whitespace: Replacing Multiple Spaces with One

Discover how to clean up user input or text content by replacing sequences of one or more whitespace characters (spaces, tabs, newlines) with a single space.

const textWithExtraSpaces = "Hello   world!  How are you   today?";
const singleSpaceText = textWithExtraSpaces.replace(/\s+/g, ' ');
console.log(singleSpaceText); // Output: "Hello world! How are you today?"

const textWithNewlines = "Line 1

Line 2 \t with tabs.";
const cleanedNewlines = textWithNewlines.replace(/\s+/g, ' ');
console.log(cleanedNewlines); // Output: "Line 1 Line 2 with tabs."

const trimmedAndCleaned = textWithExtraSpaces.replace(/\s+/g, ' ').trim();
console.log(trimmedAndCleaned); // Output: "Hello world! How are you today?"
How it works: This JavaScript snippet uses the regular expression `/\s+/g` to replace one or more whitespace characters (spaces, tabs, newlines, etc.) with a single space. `\s` matches any whitespace character, and `+` ensures it matches one or more occurrences. The `g` flag performs a global replacement, affecting all occurrences in the string. An optional `trim()` can be chained to remove leading/trailing spaces resulting 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