使用javascript缩短长字符串的聪明方法

nal*_*tis 155 javascript string truncation

有没有人有一个更复杂的解决方案/库来缩短JavaScript的字符串,而不是显而易见的:

if(string.length > 25) {
    string = string.substring(0,24) + "...";
}
Run Code Online (Sandbox Code Playgroud)

Koo*_*Inc 317

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

现在你可以这样做:

var s = 'not very long';
s.trunc(25); //=> not very long
s.trunc(5); //=> not ...
Run Code Online (Sandbox Code Playgroud)

如果通过'更复杂',你的意思是截断字符串的最后一个单词边界,那么这可能是你想要的:

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;";
      };
Run Code Online (Sandbox Code Playgroud)

现在你可以这样做:

s.trunc(11,true) // => not very...
Run Code Online (Sandbox Code Playgroud)

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

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...
Run Code Online (Sandbox Code Playgroud)

  • 不要修改您不拥有的对象.http://www.nczonline.net/blog/2010/03/02/maintainable-javascript-dont-modify-objects-you-down-own/ (10认同)
  • 还应考虑具有"硬"和"软"限制,例如,如果字符串长于500个字符,则将其截断为400.这可能很有用,当用户想要查看整个文本并单击某个链接时为了它.因此,如果你只加载1或2个字符,它看起来真的很难看. (5认同)
  • 您可以考虑的一件事是在代码示例中用实际省略号(`...`)替换`&hellip;`.如果您尝试使用它与API进行交互,那么您将需要非HTML实体. (5认同)
  • `substr`的​​第二个参数是一个长度,因此应该是`substr(0,n)`而不是将它限制在第一个`n`字符. (2认同)

mwi*_*cox 55

请注意,这只需要为Firefox完成.

所有其他浏览器都支持CSS解决方案(请参阅支持表):

p {
    white-space: nowrap;
    width: 100%;                   /* IE6 needs any width */
    overflow: hidden;              /* "overflow" value must be different from  visible"*/ 
    -o-text-overflow: ellipsis;    /* Opera < 11*/
    text-overflow:    ellipsis;    /* IE, Safari (WebKit), Opera >= 11, FF > 6 */
}
Run Code Online (Sandbox Code Playgroud)

具有讽刺意味的是,我从Mozilla MDC获得了代码片段.

  • 非常好的CSS方法.可能有一个注释,这只适用于单行文本(如`white-space:nowrap;`所预期的那样).当谈到多行时,你会遇到JavaScript问题. (7认同)

ooo*_*ala 20

使用lodash的truncate

_.truncate('hi-diddly-ho there, neighborino');
// ? 'hi-diddly-ho there, neighbo…'
Run Code Online (Sandbox Code Playgroud)

或者underscore.string的截断.

_('Hello world').truncate(5); => 'Hello...'
Run Code Online (Sandbox Code Playgroud)


Ada*_*ett 19

人们可能希望在JavaScript而不是CSS中执行此操作是有正当理由的.

要在JavaScript中截断为8个字符(包括省略号):

short = long.replace(/(.{7})..+/, "$1&hellip;");
Run Code Online (Sandbox Code Playgroud)

要么

short = long.replace(/(.{7})..+/, "$1…");
Run Code Online (Sandbox Code Playgroud)


Afr*_*mad 13

('long text to be truncated').replace(/(.{250})..+/, "$1…");
Run Code Online (Sandbox Code Playgroud)

不知何故,上面的代码不适用于 vuejs 应用程序中的某种复制粘贴或书面文本。所以我使用了lodash truncate,它现在工作正常。

_.truncate('long text to be truncated', { 'length': 250, 'separator': ' '});
Run Code Online (Sandbox Code Playgroud)


小智 7

这是我的解决方案,与其他建议相比有一些改进:

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;"
Run Code Online (Sandbox Code Playgroud)

它:

  • 在25个字符后截断第一个空格
  • 扩展JavaScript String对象,因此可以在任何字符串上使用(并链接).
  • 如果截断导致尾随空格,将修剪字符串;
  • 如果截断的字符串超过25个字符,将添加unicode hellip实体(省略号)


Sea*_*ean 7

所有现代浏览器现在都支持一个简单的 CSS 解决方案,用于在一行文本超出可用宽度时自动添加省略号:

p {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}
Run Code Online (Sandbox Code Playgroud)

(请注意,这需要以某种方式限制元素的宽度才能产生任何效果。)

基于https://css-tricks.com/snippets/css/truncate-string-with-ellipsis/

应当指出的是,这种方法并没有基于字符数限制。它也没有,如果你需要允许多行文本工作。

  • 这仅对单行句子有用,没有办法(到目前为止我知道)通过 CSS 做一个多行示例。 (2认同)

小智 7

我喜欢使用 .slice() 第一个参数是起始索引,第二个参数是结束索引。介于两者之间的一切都是你得到的。

var long = "hello there! Good day to ya."
// hello there! Good day to ya.

var short  = long.slice(0, 5)
// hello
Run Code Online (Sandbox Code Playgroud)

  • 最简单的答案,不需要过于复杂的答案。 (2认同)

Jim*_*ato 6

大多数现代JavaScript框架(JQuery的原型...)都上涨到字符串处理这一实用功能。

这是原型中的一个例子:

'Some random text'.truncate(10);
// -> 'Some ra...'
Run Code Online (Sandbox Code Playgroud)

这似乎是您希望其他人处理/维护的功能之一。我会让框架处理它,而不是编写更多的代码。

  • 我不认为 jQuery 对此有任何帮助。 (8认同)
  • Pure Underscore 似乎也没有 `truncate()` - 您可能需要一个扩展名,例如 [underscore.string](https://github.com/epeli/underscore.string) 。 (3认同)
  • 这完全是正确的答案。我不知道下划线,但 lodash 有`_.trunc` 正是这样做的。 (3认同)
  • Underscore.js 确实 - _('Hello world').truncate(5) =&gt; 'Hello...' _('Hello').truncate(10) =&gt; 'Hello' (2认同)
  • 我认为正确的答案是使用 lodash.trunc 或 underscore.string.truncate。 (2认同)

Jef*_*dez 6

我发现的最佳功能。归功于文字省略号

function textEllipsis(str, maxLength, { side = "end", ellipsis = "..." } = {}) {
  if (str.length > maxLength) {
    switch (side) {
      case "start":
        return ellipsis + str.slice(-(maxLength - ellipsis.length));
      case "end":
      default:
        return str.slice(0, maxLength - ellipsis.length) + ellipsis;
    }
  }
  return str;
}
Run Code Online (Sandbox Code Playgroud)

例子

var short = textEllipsis('a very long text', 10);
console.log(short);
// "a very ..."

var short = textEllipsis('a very long text', 10, { side: 'start' });
console.log(short);
// "...ng text"

var short = textEllipsis('a very long text', 10, { textEllipsis: ' END' });
console.log(short);
// "a very END"
Run Code Online (Sandbox Code Playgroud)