Installation
Quick Take
The Purpose
It is a function which trims a given string, to accommodate the “X letters wide (opts.maxLen
), Y lines-long (opts.maxLines
)” cramped spaces such as aside
UI components.
You can see it here, on this page, on the sidebar on the right ⤴
Features
- Super lightweight
- Extremely performant
- Multilingual — supports all alphabets: Latin (from English to Lithuanian), Cyrillic (from Russian to Chechen) and Hebrew
- Two trusted dependencies only: one our own and one from
lodash
- Source in TS
- Automatically-generated type definitions
- Supports native ES Modules
- Browser-Compatible
- 100% code coverage unit tests
API — truncate()
The main function truncate()
is imported like this:
It’s a function which takes two input arguments:
Input argument | Type | Obligatory | Description |
---|---|---|---|
str Type: String Obligatory: yes | |||
str | String | yes | The string in which you want to perform a search |
opts Type: Plain object Obligatory: no | |||
opts | Plain object | no | Optional Options Object. |
None of the input arguments will be mutated by this program; we have unit tests to prove that.
The Optional Options Object has the following shape:
Key | Type | Default | Description |
---|---|---|---|
maxLen Type: Number Default: 10 | |||
maxLen | Number | 10 | How many lengths of the longest character from opts.letterWidths is allowed per-line? |
maxLines Type: Number Default: 2 | |||
maxLines | Number | 2 | How many lines are allowed, maximum? |
ellipsisLen Type: Number Default: 155 | |||
ellipsisLen | Number | 155 | Optionally, override the ellipsis length to optimise the calculations. |
monospace Type: Boolean Default: false | |||
monospace | Boolean | false | Optionally, disable the letter lengths being used. When enabled, it crops by the character count, as if it was a monospace font. |
noEmpty Type: Boolean Default: true | |||
noEmpty | Boolean | true | Optionally, you can disable the throwing when the empty string argument has been passed. |
letterWidths Type: Plain object Default: see below | |||
letterWidths | Plain object | see below | While the default set here is based on “Outfit” font letter widths, you can pass your own font’s widths for each letter. |
The function will return a plain object:
Key’s name | Type | Description |
---|---|---|
result Type: String | ||
result | String | A truncated string |
addEllipsis Type: Boolean | ||
addEllipsis | Boolean | Should you append an ellipsis (… /\u2026 ) or not. |
API — defaults
You can import defaults
:
It's a plain object:
The main function calculates the options to be used by merging the options you passed with these defaults.
PS. Sorry the Hebrew characters are right-to-left, they display JSON lines the other way-around ↑
The opts.letterWidths
are based on Outfit font, as used on this website. You are free to re-use the settings as-is or override them with your font’s widths.
API — version
You can import version
: