Does anyone have a more sophisticated solution/library for truncating strings with JavaScript and putting an ellipsis on the end, than the obvious one:
if (string.length > 25) {
string = string.substring(0, 24) + "...";
}
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Essentially, you check the length of the given string. If it’s longer than a given length
n, clip it to lengthn(substrorslice) and add html entity…(…) to the clipped string.Such a method looks like
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
You can extend the native
Stringprototype with your function. In that case thestrparameter should be removed andstrwithin the function should be replaced withthis:More dogmatic developers may chide you strongly for that ("Don’t modify objects you don’t own". I wouldn’t mind though). [edit 2023] A method to extend the String without tampering with its prototype may be to use a
Proxy. See this stackblitz snippet.An approach without extending the
Stringprototype is to createyour own helper object, containing the (long) string you provide
and the beforementioned method to truncate it. That’s what the snippet
below does.
Finally, you can use css only to truncate long strings in HTML nodes. It gives you less control, but may well be viable solution.