CyrefJS
CCyrefJS
فا
Back to documentation
String/Since 1.38.0

truncate

Shortens a string to a maximum length and appends an omission string when truncation is required.

truncate(value, length, omission):string

Length validation

The length parameter must be a non-negative integer. Otherwise, truncate throws a RangeError with the message: "truncate: length must be a non-negative integer".

Unicode-aware length

The input and omission are converted with Array.from before their lengths are evaluated or characters are sliced. This means Unicode code points such as surrogate-pair emoji are treated as single characters.

Omission behavior

The default omission is "...". If the omission length is greater than or equal to the requested length, only the first length code points of the omission are returned. Otherwise, the original string is shortened enough to leave room for the complete omission.

Return behavior

If the input already fits within the requested length, the original value is returned. If truncation is required, the returned string consists of the retained portion followed by the omission.

Parameters

valuestringrequired

The string to truncate.

lengthnumberrequired

The maximum number of Unicode code points allowed in the result.

omissionstringoptional

The string appended when the value needs to be truncated.

Default:"..."

Returns

string

The original string when it fits within the requested length, or a truncated string with the omission appended.

Errors

Throws a RangeError if length is not a non-negative integer.

Examples

01

Basic usage

Long text is shortened and the default omission is appended.

TypeScript
truncate("Hello World", 8);
// "Hello..."
02

Custom omission

A custom omission string can be provided.

TypeScript
truncate("Hello World", 8, "…");
// "Hello W…"
03

Value already fits

If the string length is already within the requested limit, the original value is returned unchanged.

TypeScript
truncate("Hello", 10);
// "Hello"
04

Length shorter than omission

When the omission itself is at least as long as the requested length, only the beginning of the omission is returned.

TypeScript
truncate("Hello World", 2, "...");
// ".."
05

Zero length

A zero length returns an empty string when truncation is required.

TypeScript
truncate("Hello", 0);
// ""
06

Unicode characters

Truncation counts Unicode code points using Array.from.

TypeScript
truncate("Hello 😀 World", 8);
// "Hello 😀..."
07

Empty value

An empty input always returns an empty string.

TypeScript
truncate("", 5);
// ""
Built with@cyref/js·Official documentation