0

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?

Tommy Brunn
  • 2,520
  • 2
  • 29
  • 41
  • Related to http://stackoverflow.com/questions/536814/insert-ellipsis-into-html-tag-if-content-too-wide – Soren Sep 06 '11 at 15:46

1 Answers1

2

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) + '...';
}
Marc B
  • 356,200
  • 43
  • 426
  • 500
  • You may want tot use lastIndexOf() instead so as to get the rightmost space. – Soren Sep 06 '11 at 15:46
  • Doesn't really matter, if I'm reading the question right. The presence of ANY space anywhere in the string means no ellipsis is needed. – Marc B Sep 06 '11 at 15:54
  • Worked great. I had to add a check to see if the string was shorter than N, but other than that, worked fine. Thanks! – Tommy Brunn Sep 06 '11 at 16:26