本文介绍了使用javascript缩短长字符串的聪明方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有人有一个更复杂的解决方案/库来缩短使用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)+"...";
}


推荐答案

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

现在你可以这样做:

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

如果更复杂,则意味着截断a的最后一个字边界字符串,那么这可能是你想要的:

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 ){
         if (this.length <= n) { return this; }
         var subString = this.substr(0, n-1);
         return (useWordBoundary
            ? subString.substr(0, subString.lastIndexOf(' '))
            : subString) + "&hellip;";
      };

现在你可以这样做:

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

如果您不想扩展本机对象,可以使用:

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

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

这篇关于使用javascript缩短长字符串的聪明方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 04:40