anyone have a handy method to truncate a string in the middle? Something like:
truncate ('abcdefghi', 8);
would result in
'abc...hi'
UPDATE:
to be a bit more complete
Essentially, you check the length of the given string. If it's longer than a given length n , clip it to length n ( substr or slice ) and add html entity … (…) to the clipped string. function truncate( str, n, useWordBoundary ){ if (str. length <= n) { return str; } const subString = str.
In JavaScript, trunc() is a function that is used to return the integer portion of a number. It truncates the number and removes all fractional digits. Because the trunc() function is a static function of the Math object, it must be invoked through the placeholder object called Math.
Make a loop at the end of the string. After cutting the string at the proper length, take the end of the string and tie a knot at the very end, then fold the string over and tie a loop, about the same size as the original loop (about 2cm in diameter).
Something like this...
function truncate(text, startChars, endChars, maxLength) {
if (text.length > maxLength) {
var start = text.substring(0, startChars);
var end = text.substring(text.length - endChars, text.length);
while ((start.length + end.length) < maxLength)
{
start = start + '.';
}
return start + end;
}
return text;
}
alert(truncate('abcdefghi',2,2,8));
Or to limit to true ellipsis:
function truncate(text, startChars, endChars, maxLength) {
if (text.length > maxLength) {
var start = text.substring(0, startChars);
var end = text.substring(text.length - endChars, text.length);
return start + '...' + end;
}
return text;
}
alert(truncate('abcdefghi',2,2,8));
jsFiddle
Here's one way to do it chopping up the string with substr
:
var truncate = function (fullStr, strLen, separator) {
if (fullStr.length <= strLen) return fullStr;
separator = separator || '...';
var sepLen = separator.length,
charsToShow = strLen - sepLen,
frontChars = Math.ceil(charsToShow/2),
backChars = Math.floor(charsToShow/2);
return fullStr.substr(0, frontChars) +
separator +
fullStr.substr(fullStr.length - backChars);
};
See example →
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With