Truncates a string up to specified length, respecting whitespace when possible.
String.prototype.length
is greater or equal to lim
. If not, return it as-is.String.prototype.slice()
and String.prototype.lastIndexOf()
to find the index of the last space below the desired lim
.String.prototype.slice()
to appropriately truncate str
based on lastSpace
, respecting whitespace if possible and appending ending
at the end.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...'
JavaScript, String
Truncates a string up to a specified length.
JavaScript, String
Generates a random string with the specified length.
JavaScript, String
Pads a string on both sides with the specified character, if it's shorter than the specified length
.