有没有人比显而易见的解决方案/库更复杂的解决方案/库,用于使用JavaScript截断字符串并在末尾添加省略号:
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 ...
如果“更复杂”是指在字符串的最后一个单词边界处截断,那么这可能就是您想要的:
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) + "…"; };
s.trunc(11,true) // => not very...
如果您不想扩展本机对象,则可以使用:
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) + "…"; }; // usage truncate.apply(s, [11, true]); // => not very...