naltatis naltatis - 2 months ago 19
Javascript Question

smart way to shorten long strings with javascript

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)+"...";
}

Answer
String.prototype.trunc = String.prototype.trunc ||
      function(n){
          return (this.length > n) ? this.substr(0,n-1)+'…' : this;
      };

Now you can do:

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

If by 'more sophisticated', you mean truncating at the last word boundary of a string, then this might be what you want:

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

now you can do:

s.trunc(11,true) //=>not very...

If you don't want to extend native objects, you can use:

function truncate( n, useWordBoundary ){
    var isTooLong = this.length > n,
        s_ = isTooLong ? this.substr(0,n-1) : this;
        s_ = (useWordBoundary && isTooLong) ? s_.substr(0,s_.lastIndexOf(' ')) : s_;
    return  isTooLong ? s_ + '…' : s_;
};
// usage
truncate.apply(s, [11, true]); //=>not very...
Comments