Skip to content

truncateToNearestWord() ​

truncateToNearestWord(input, maxLength): string

Defined in: utils/string/truncateToNearestWord.ts:29

Truncate a string to the nearest whole word within a given length limit. If the string exceeds the max length, it appends '...' at the end. If no space is found within the truncated string, and the string is longer than the max length, it will truncate the string at the max length and append '...'.

Parameters ​

input ​

string

The raw input string to be truncated.

maxLength ​

number

The maximum length of the truncated string (including ellipsis if applied).

Returns ​

string

  • The truncated string that does not break words, with an optional ellipsis.

Examples ​

ts
truncateToNearestWord("This is a very long sentence that needs truncation.", 20);
// Returns: "This is a very..."
ts
truncateToNearestWord("Short sentence.", 50);
// Returns: "Short sentence." (no truncation applied)
ts
truncateToNearestWord("Exact length match!", 20);
// Returns: "Exact length match!"

Released under the MIT License.