views:

1756

answers:

6

Does anyone have a more sophisticated solution/library for shortening strings with JavaScript, than the obvious one:

if(string.length > 25) {
    string = string.substring(0,24)+"...";
}
A: 

With a quick googling I found this... Can do?

Manrico Corazzi
+3  A: 
String.prototype.trunc = function(n){
                          return this.substr(0,n-1)+(this.length>n?'...':'');
                         };

Now you can do:

var s = 'not very long';
s.trunc(25); //=> not very long
s.trunc(5); //=> not ...

if you mean truncating at the last word boundary of a string with 'more sophisticated' then this may be what you want:

String.prototype.trunc =
     function(n,useWordBoundary){
         var toLong = this.length>n,
             s_ = toLong ? this.substr(0,n-1) : this;
         s_ = useWordBoundary && toLong ? s_.substr(0,s_.lastIndexOf(' ')) : s_;
         return  toLong ? s_ +'...' : s_;
      };

now you can do:

s.trunc(11,true) //=>not very...
KooiInc
Should also consider having "hard" and "soft" limits, like, for example, if the string is longer than 500 character, truncate it to 400. This may be useful, when the user wants to see the whole text and clicks some link for it. If, as a result, you load just 1 or 2 chars more, it will look really ugly.
maksymko
A: 

Most modern Javascript frameworks (JQuery, Prototype, etc...) have a utility function tacked on to String that handles this.

Here's an example in Prototype:

'Some random text'.truncate(10);
// -> 'Some ra...'

This seems like one of those functions you want someone else to deal with/maintain. I'd let the framework handle it, rather than writing more code.

Jim Fiorato
A: 

Here's my solution, which has a few improvements over other suggestions:

String.prototype.truncate = function(){
    var re = this.match(/^.{0,25}[\S]*/);
    var l = re[0].length;
    var re = re[0].replace(/\s$/,'');
    if(l < this.length)
        re = re + "&hellip;";
    return re;
}

// "This is a short string".truncate();
"This is a short string"

// "Thisstringismuchlongerthan25characters".truncate();
"Thisstringismuchlongerthan25characters"

// "This string is much longer than 25 characters and has spaces".truncate();
"This string is much longer&hellip;"

It:

  • Truncates on the first space after 25 characters
  • Extends the JavaScript String object, so it can be used on (and chained to) any string.
  • Will trim the string if truncation results in a trailing space;
  • Will add the unicode hellip entity (ellipsis) if the truncated string is longer than 25 characters
cpharmston
+2  A: 

Note that this only needs to be done for Firefox. All other browsers support a CSS solution:

p {
    white-space: nowrap;
    width: 100%;                   /* IE6 needs any width */
    overflow: hidden;              /* "overflow" value must be different from "visible"*/ 
    -o-text-overflow: ellipsis;    /* Opera */
    text-overflow:    ellipsis;    /* IE, Safari (WebKit) */
}

The irony is I got that code snippet from Mozilla MDC.

mwilcox
Yep, Firefox sucks!
Josh Stodola
Firefox doesn't suck.
mwilcox
A: 

Just another method you can use for truncating large text strings

function truncate( text, length, ellipsis )
{
   // length ( default = 20 )
   if (typeof length == 'undefined') var length = 20;

   // ellipsis display ( default = "..." )
   if (typeof ellipsis == 'undefined') var ellipsis = '...';

   // if text length does not exceed limit then return text as is 
   if (text.length < length) return text; 

   // convert text string
   for (var i = length-1; text.charAt(i) != ' '; i--) {
     length--;
   }

   return text.substr(0, length) + ellipsis;
}
Kieran