1.38.0normalizeWhitespace
Normalizes whitespace in a string by replacing consecutive whitespace characters with a single space and trimming leading and trailing whitespace.
normalizeWhitespace(value):stringBehavior
normalizeWhitespace replaces every sequence of one or more whitespace characters with a single space, then removes whitespace from the beginning and end of the string.
Whitespace handling
The regular expression uses the Unicode-aware whitespace character class, so whitespace matched by JavaScript's Unicode regular expression behavior is normalized.
Collapsing whitespace
Consecutive whitespace characters are collapsed into exactly one regular space character.
Trimming
After whitespace sequences are normalized, trim removes any remaining whitespace from the beginning and end of the result.
Parameters
valuestringrequiredThe string whose whitespace should be normalized.
Returns
stringThe string with consecutive whitespace collapsed into single spaces and leading and trailing whitespace removed.
Examples
Basic usage
Collapse multiple spaces into a single space.
import { normalizeWhitespace } from "@cyref/js";
normalizeWhitespace("hello world");
// "hello world"Leading and trailing whitespace
Leading and trailing whitespace is removed.
normalizeWhitespace(" hello world ");
// "hello world"Tabs and newlines
Whitespace characters such as tabs and newlines are normalized to single spaces.
normalizeWhitespace("hello\t\nworld");
// "hello world"Mixed whitespace
Different consecutive whitespace characters are collapsed into one space.
normalizeWhitespace("hello \t \n world");
// "hello world"Empty string
An empty string remains empty.
normalizeWhitespace("");
// ""Whitespace-only string
A string containing only whitespace becomes an empty string.
normalizeWhitespace(" \t\n ");
// ""Already normalized
A string with normal spacing remains unchanged.
normalizeWhitespace("hello world");
// "hello world"