3

Shorten a string to length while preserving full word

Function JavaScript 1 revisions 630 2 years ago 2 years ago
function shorten(str, len, ellipsis = '…') {
	if (str.length <= len)
		return str;
	
	var result = str.substr(0, len - 1);
	result = result.substr(0, Math.min(result.length, result.lastIndexOf(" ")));

	return result + ellipsis;
}

Use like:

shorten('this is a long string', 12);       // this is a…
shorten('this is a long string', 2);        // …
shorten('this is a long string', 50);       // this is a long string
shorten('this is a long string', 12, '..'); // this is a..