1.2 KiB
1.2 KiB
title, tags, cover, firstSeen, lastUpdated
| title | tags | cover | firstSeen | lastUpdated |
|---|---|---|---|---|
| Truncate string at whitespace | string | cloudy-mountaintop-2 | 2020-10-19T11:11:16+03:00 | 2020-10-21T21:17:45+03:00 |
Truncates a string up to specified length, respecting whitespace when possible.
- Determine if
String.prototype.lengthis greater or equal tolim. If not, return it as-is. - Use
String.prototype.slice()andString.prototype.lastIndexOf()to find the index of the last space below the desiredlim. - Use
String.prototype.slice()to appropriately truncatestrbased onlastSpace, respecting whitespace if possible and appendingendingat the end. - Omit the third argument,
ending, to use the default ending of'...'.
const truncateStringAtWhitespace = (str, lim, ending = '...') => {
if (str.length <= lim) return str;
const lastSpace = str.slice(0, lim - ending.length + 1).lastIndexOf(' ');
return str.slice(0, lastSpace > 0 ? lastSpace : lim - ending.length) + ending;
};
truncateStringAtWhitespace('short', 10); // 'short'
truncateStringAtWhitespace('not so short', 10); // 'not so...'
truncateStringAtWhitespace('trying a thing', 10); // 'trying...'
truncateStringAtWhitespace('javascripting', 10); // 'javascr...'