CyrefJS
CCyrefJS
فا
Back to documentation
String/Since 1.38.0

normalizeWhitespace

Normalizes whitespace in a string by replacing consecutive whitespace characters with a single space and trimming leading and trailing whitespace.

normalizeWhitespace(value):string

Behavior

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

valuestringrequired

The string whose whitespace should be normalized.

Returns

string

The string with consecutive whitespace collapsed into single spaces and leading and trailing whitespace removed.

Examples

01

Basic usage

Collapse multiple spaces into a single space.

TypeScript
import { normalizeWhitespace } from "@cyref/js";

normalizeWhitespace("hello    world");
// "hello world"
02

Leading and trailing whitespace

Leading and trailing whitespace is removed.

TypeScript
normalizeWhitespace("   hello world   ");
// "hello world"
03

Tabs and newlines

Whitespace characters such as tabs and newlines are normalized to single spaces.

TypeScript
normalizeWhitespace("hello\t\nworld");
// "hello world"
04

Mixed whitespace

Different consecutive whitespace characters are collapsed into one space.

TypeScript
normalizeWhitespace("hello \t \n world");
// "hello world"
05

Empty string

An empty string remains empty.

TypeScript
normalizeWhitespace("");
// ""
06

Whitespace-only string

A string containing only whitespace becomes an empty string.

TypeScript
normalizeWhitespace(" \t\n ");
// ""
07

Already normalized

A string with normal spacing remains unchanged.

TypeScript
normalizeWhitespace("hello world");
// "hello world"
Built with@cyref/js·Official documentation