Smart way to truncate long strings
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.
Such a method looks like
function truncate(str, n){
return (str.length > n) ? str.substr(0, n-1) + '…' : str;
};
If by 'more sophisticated' you mean truncating at the last word boundary of a string then you need an extra check. First you clip the string to the desired length, next you clip the result of that to its last word boundary
function truncate( str, n, useWordBoundary ){
if (str.length <= n) { return str; }
const subString = str.substr(0, n-1); // the original check
return (useWordBoundary
? subString.substr(0, subString.lastIndexOf(" "))
: subString) + "…";
};
You can extend the native String
prototype with your function. In that case the str
parameter should be removed and str
within the function should be replaced with this
:
String.prototype.truncate = String.prototype.truncate ||
function ( n, useWordBoundary ){
if (this.length <= n) { return this; }
const subString = this.substr(0, n-1); // the original check
return (useWordBoundary
? subString.substr(0, subString.lastIndexOf(" "))
: subString) + "…";
};
More dogmatic developers may chide you strongly for that ("Don't modify objects you don't own". I wouldn't mind though).
An approach without extending the String
prototype is to create
your own helper object, containing the (long) string you provide
and the beforementioned method to truncate it. That's what the snippet
below does.
const LongstringHelper = str => {
const sliceBoundary = str => str.substr(0, str.lastIndexOf(" "));
const truncate = (n, useWordBoundary) =>
str.length <= n ? str : `${ useWordBoundary
? sliceBoundary(str.slice(0, n - 1))
: str.substr(0, n - 1)}…`;
return { full: str, truncate };
};
const longStr = LongstringHelper(`Lorem ipsum dolor sit amet, consectetur
adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore
magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation
ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute
irure dolor in reprehenderit in voluptate velit esse cillum dolore
eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum`);
const plain = document.querySelector("#resultTruncatedPlain");
const lastWord = document.querySelector("#resultTruncatedBoundary");
plain.innerHTML =
longStr.truncate(+plain.dataset.truncateat, !!+plain.dataset.onword);
lastWord.innerHTML =
longStr.truncate(+lastWord.dataset.truncateat, !!+lastWord.dataset.onword);
document.querySelector("#resultFull").innerHTML = longStr.full;
body {
font: normal 12px/15px verdana, arial;
}
p {
width: 450px;
}
#resultTruncatedPlain:before {
content: 'Truncated (plain) n='attr(data-truncateat)': ';
color: green;
}
#resultTruncatedBoundary:before {
content: 'Truncated (last whole word) n='attr(data-truncateat)': ';
color: green;
}
#resultFull:before {
content: 'Full: ';
color: green;
}
<p id="resultTruncatedPlain" data-truncateat="120" data-onword="0"></p>
<p id="resultTruncatedBoundary" data-truncateat="120" data-onword="1"></p>
<p id="resultFull"></p>
Finally, you can use css only to truncate long strings in HTML nodes. It gives you less control, but may well be viable solution.
body {
font: normal 12px/15px verdana, arial;
margin: 2rem;
}
.truncate {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
width: 30vw;
}
.truncate:before{
content: attr(data-longstring);
}
.truncate:hover::before {
content: attr(data-longstring);
width: auto;
height: auto;
overflow: initial;
text-overflow: initial;
white-space: initial;
background-color: white;
display: inline-block;
}
<div class="truncate" data-longstring="Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."></div>
Note that this only needs to be done for Firefox.
All other browsers support a CSS solution (see support table):
p {
white-space: nowrap;
width: 100%; /* IE6 needs any width */
overflow: hidden; /* "overflow" value must be different from visible"*/
-o-text-overflow: ellipsis; /* Opera < 11*/
text-overflow: ellipsis; /* IE, Safari (WebKit), Opera >= 11, FF > 6 */
}
The irony is I got that code snippet from Mozilla MDC.