Note #3

I see a lot of bad text trimming code around. It usually cuts off a word mid-way through, which just looks bad. This code aligns the ellipses with the start and end of words. It returns a tuple. This approach can obviously be used in any language.

const trimText = (input: string, length: number = 80): [text: string, trimmed: boolean] => {
const trimmed = input.length >= length;
const text = trimmed ? `${input.slice(0, input.lastIndexOf(' ', length))}...` : input;
return [text, trimmed];
trimText('This is some trimmed text that will not cut off half way through a word.', 35)
// => ['This is some trimmed text that will...', true]

Read the rest of my notes

© Lloyd Atkinson 2024 ✌

I'm available for work 💡