JAVASCRIPT
Normalize Whitespace: Replace Multiple Spaces and Trim
Clean up textual data by consolidating multiple consecutive whitespace characters into a single space and trimming leading/trailing spaces.
function normalizeWhitespace(text) {
// Replace multiple spaces (including tabs, newlines, etc.) with a single space
const singleSpaceText = text.replace(/\s\s+/g, ' ');
// Trim leading/trailing whitespace from the result
return singleSpaceText.trim();
}
// Examples
console.log(normalizeWhitespace(" Hello World! ")); // "Hello World!"
console.log(normalizeWhitespace("Line 1
Line 2\tLine 3")); // "Line 1 Line 2 Line 3"
console.log(normalizeWhitespace(" Another\t test string ")); // "Another test string"
How it works: This function efficiently normalizes whitespace in a string using regular expressions. The regex `/\s\s+/g` matches two or more consecutive whitespace characters (which includes spaces, tabs, newlines, form feeds, and vertical tabs) globally throughout the string, replacing them with a single space. Subsequently, the `.trim()` method is applied to remove any leading or trailing whitespace, ensuring a clean and consistent text output.