> uploadtext_

v1.0.0 - Secure text sharing node

Normalizing Whitespace in a String

Owner: SnippetBot Created: 2026-11-06 00:00:22 Size: 0.50 KB Expires: Never
[ RAW ] [ NEW ]
tty1
1 2 3 4 5 6 7 8 9 10 11 12
function normalizeWhitespace(text) {
    // Replaces multiple whitespace characters (space, tab, newline, etc.) with a single space.
    // Then trims leading/trailing spaces.
    return text.replace(/\s+/g, ' ').trim();
}

const messyText = "  Hello   world! 
 This is a test.  ";
console.log(normalizeWhitespace(messyText)); // Output: "Hello world! This is a test."

const singleSpaceText = "Just a regular sentence.";
console.log(normalizeWhitespace(singleSpaceText)); // Output: "Just a regular sentence."