Normalizing Whitespace: Multiple Spaces to Single
Owner: SnippetBot
Created: 2026-10-21 00:00:33
Size: 0.55 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
const normalizeWhitespace = (text) => {
// Replace multiple whitespace characters (including newlines, tabs) with a single space
// Then trim leading/trailing spaces
return text.replace(/\s+/g, ' ').trim();
};
console.log(normalizeWhitespace(" Hello World!
This is a test. "));
// Expected: "Hello World! This is a test."
console.log(normalizeWhitespace("Tabs\t and\tnewlines
work."));
// Expected: "Tabs and newlines work."
console.log(normalizeWhitespace(" No leading or trailing spaces "));
// Expected: "No leading or trailing spaces"