Tommy Brunn
Tommy Brunn

Reputation: 2562

Truncate strings that have no whitespace

I'm having an issue where some strings are overflowing their container. I can, of course use overflow:hidden, but it doesn't look that great as I would prefer text-overflow: ellipsis. However, the cross-platform support for that is iffy at best, and the existing solutions I've found don't allow the string to wrap if it contains spaces.

So, my workaround is to truncate the strings in Javascript if the string doesn't contain any spaces for the first N characters. Obviously it won't work as intended if the user doesn't have the correct font installed or if they're zoomed in, but in that case, overflow:hidden will kick in, so I'm okay with that.

Now my question is, how can I do this in as efficient a manner as possible? Will I have to loop through the first N characters and see if each one is a space, and if none of them are, do a string.substring(0, N-3) and then append an ellipsis to it?

Upvotes: 0

Views: 363

Answers (1)

Marc B
Marc B

Reputation: 360762

Shouldn't have to loop to do simple "is there a space" detection:

var shortened = yourstring.substr(0,N);
if (shortened.indexOf(' ') == -1) {
   var shortened = shortened.substr(0, N-3) + '...';
}

Upvotes: 2

Related Questions