Skip to content
Advertisement

Smart way to truncate long strings

Does anyone have a more sophisticated solution/library for truncating strings with JavaScript and putting an ellipsis on the end, than the obvious one:

JavaScript

Advertisement

Answer

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

JavaScript

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

JavaScript

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:

JavaScript

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.

JavaScript
JavaScript
JavaScript

Finally, you can use css only to truncate long strings in HTML nodes. It gives you less control, but may well be viable solution.

JavaScript
JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement