string-truncate
v1.0.0
Published
Truncate a string with a custom separator in the middle (tru…ate), end (trunca…) or at any index (t…ncate).
Maintainers
Readme
string-truncate
Truncate a string with a custom separator in the middle (tru…ate), end (trunca…) or at any index (t…ncate).
Installation
npm install string-truncateUsage
import { 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: "..." }));
// => ".."API
Constants
Functions
Typedefs
DEFAULT_SEPARATOR : string
Default separator used for truncation ("…" - horizontal ellipsis)
Kind: global constant
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).
Kind: global function
| Param | Type | Default | | --------- | ------------------------------------------------ | --------------- | | string | string | | | [length] | number | 10 | | [options] | TruncateOptions | {} |
truncateMiddle(string, [length], [options]) ⇒ string
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 | {} |
TruncateOptions : object
Kind: global typedef Properties
| Name | Type | Default | | ---------------- | ------------------- | ------------------------------------------ | | [separatorIndex] | number | Infinity | | [separator] | string | "DEFAULT_SEPARATOR" |
License
MIT. See license file.
