如何在jQuery中截断字符串?

hd.*_*hd. 61 javascript string jquery

我有很长的头衔,想要截断它们但是在某种程度上没有任何文字突破,我的意思是切割发生在不切词的单词之间.

我怎么能用jquery呢?

Nav*_*eed 123

来自: jQuery文本截断(阅读更多样式)

试试这个:

var title = "This is your title";

var shortText = jQuery.trim(title).substring(0, 10)
    .split(" ").slice(0, -1).join(" ") + "...";
Run Code Online (Sandbox Code Playgroud)

你也可以使用插件:

作为String的扩展

String.prototype.trimToLength = function(m) {
  return (this.length > m) 
    ? jQuery.trim(this).substring(0, m).split(" ").slice(0, -1).join(" ") + "..."
    : this;
};
Run Code Online (Sandbox Code Playgroud)

用于

"This is your title".trimToLength(10);
Run Code Online (Sandbox Code Playgroud)

  • 这是一个边缘情况,但如果标题的第一个单词是10个或更多字符,则返回"..." (3认同)

小智 40

如果原始字符串没有空格,则上述解决方案将不起作用.

试试这个:

var title = "This is your title";
var shortText = jQuery.trim(title).substring(0, 10)
                          .trim(this) + "...";
Run Code Online (Sandbox Code Playgroud)

  • 当字符串短于10个字符时,这会添加省略(三个点)> jQuery.trim("test").substring(0,10).trim(this)+"..."; "测试..." (2认同)

Kea*_*ang 36

  function truncateString(str, length) {
     return str.length > length ? str.substring(0, length - 3) + '...' : str
  }
Run Code Online (Sandbox Code Playgroud)

  • 如果字符串比最大长度短,则唯一的答案是不添加点.并包括计算中的点... (4认同)

Ram*_*aja 7

而不是使用jQuery,使用css属性text-overflow:ellipsis.它会自动截断字符串.

.truncated { display:inline-block; 
             max-width:100px; 
             overflow:hidden; 
             text-overflow:ellipsis; 
             white-space:nowrap; 
           }
Run Code Online (Sandbox Code Playgroud)