JAVASCRIPT
Condense Multiple Spaces to Single Space
A simple yet effective JavaScript regex for normalizing text by replacing all sequences of two or more spaces with a single space, improving text readability.
function condenseSpaces(text) {
// Replace sequences of two or more whitespace characters with a single space
let cleanedText = text.replace(/\s{2,}/g, ' ');
// Trim leading/trailing spaces that might result from replacement
cleanedText = cleanedText.trim();
return cleanedText;
}
// Examples:
// console.log(condenseSpaces("This is a test.")); // "This is a test."
// console.log(condenseSpaces(" Leading and trailing spaces. ")); // "Leading and trailing spaces."
// console.log(condenseSpaces("Single spaces are fine.")); // "Single spaces are fine.")
How it works: This JavaScript function `condenseSpaces` takes a string and uses a regular expression (`/\s{2,}/g`) to replace any sequence of two or more whitespace characters (`\s`) with a single space. The `g` flag ensures all occurrences are replaced. Additionally, `trim()` is used to remove any leading or trailing spaces that might remain after the replacement, providing a cleanly formatted string.