Skip to content

truncate ​

Truncates a string to a specified length and optionally adds an ending (like an ellipsis).

Syntax ​

typescript
truncate(str: string, length: number, ending?: string): string

Parameters ​

ParameterTypeDescription
strstringThe input string to be truncated.
lengthnumberThe maximum length of the truncated string.
endingstring(Optional) The string to append at the end if truncated. Default is "...".

Returns ​

TypeDescription
stringThe truncated string.

Example ​

typescript
truncate("Exemplo de string para truncar", 10); // "Exemplo..."
truncate("Teste", 10); // "Teste"
truncate("Utilify", 4, "~"); // "Uti~"

Notes ​

  • Throws TypeError if str is not a string or length is not a number.
  • If the string is shorter than or equal to the specified length, it is returned unchanged.

References ​

Released under the MIT License.