Truncate a string with a custom separator in the middle (tru…ate), end (trunca…) or at any index (t…ncate).
npm install string-truncateimport { truncate, truncateMiddle } from "string-truncate";
// Basic usage with default options
console.log(truncate("This is a long string that needs to be shortened"));
// => "This is a…"
// With custom length
console.log(truncate("0123456789", 5));
// => "0123…"
// Truncate with custom separator
console.log(truncate("0123456789abcdef", 10, { separator: "..." }));
// => "0123456..."
// Truncate with specific separator position
console.log(
truncate("0123456789abcdef", 12, { separator: "[...]", separatorIndex: 4 }),
);
// => "0123[...]def"
// Middle truncation with default separator
console.log(truncateMiddle("0123456789abcdefghij", 12));
// => "012345…fghij"
// Middle truncation with custom separator
console.log(truncateMiddle("0123456789abcdefghij", 14, { separator: "---" }));
// => "012345---fghij"
// Edge cases
console.log(truncate("short", 10)); // Returns original if shorter than length
// => "short"
// Very short length (not enough room for separator)
console.log(truncate("0123456789", 3, { separator: "..." }));
// => "..."
console.log(truncate("0123456789", 2, { separator: "..." }));
// => ".."- DEFAULT_SEPARATOR :
string Default separator used for truncation ("…" - horizontal ellipsis)
- truncate(string, [length], [options]) ⇒
string Truncate a string with a custom separator in the middle (tru…ate), end (trunca…) or at any index (t…ncate).
- truncateMiddle(string, [length], [options]) ⇒
string Truncate a string with the separator approximately in the middle of the resulting string.
- TruncateOptions :
object
Default separator used for truncation ("…" - horizontal ellipsis)
Truncate a string with a custom separator in the middle (tru…ate), end (trunca…) or at any index (t…ncate).
Kind: global function
| Param | Type | Default |
|---|---|---|
| string | string |
|
| [length] | number |
10 |
| [options] | TruncateOptions |
{} |
Truncate a string with the separator approximately in the middle of the resulting string.
Kind: global function
| Param | Type | Default |
|---|---|---|
| string | string |
|
| [length] | number |
10 |
| [options] | TruncateOptions |
{} |
Kind: global typedef Properties
| Name | Type | Default |
|---|---|---|
| [separatorIndex] | number |
Infinity |
| [separator] | string |
"DEFAULT_SEPARATOR" |
MIT. See license file.