【问题标题】:How Can I Truncate A String In jQuery?如何在 jQuery 中截断字符串?
【发布时间】:2011-01-09 06:12:28
【问题描述】:

我有很长的标题,想截断它们,但以一种没有单词中断的方式,我的意思是在单词之间进行切割而不是切割一个单词。

我如何使用 jquery 来做到这一点?

【问题讨论】:

    标签: javascript jquery string


    【解决方案1】:

    发件人: jQuery text truncation (read more style)

    试试这个:

    var title = "This is your title";
    
    var shortText = jQuery.trim(title).substring(0, 10)
        .split(" ").slice(0, -1).join(" ") + "...";
    

    你也可以使用插件:

    作为字符串的扩展

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

    用作

    "This is your title".trimToLength(10);
    

    【讨论】:

    • $.trim(title) 被建议 - 我同意,因为它也可以处理 IE
    • 这是一个边缘情况,但如果标题的第一个单词是 10 个或更多字符,则返回“...”
    • 如果它正好在单词的末尾切割,这不会失败吗?即:'Test test sentence'.trimToLength(9) 将删除第二个测试,即使它完全有效。
    • 好答案。我会选择使用…,而不是三个单独的点,但这确实是一个偏好问题。
    【解决方案2】:

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

    试试这个:

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

    【讨论】:

    • 完美!非常感谢您提供此补丁。
    • 当字符串少于10个字符时添加省略(三个点)>jQuery.trim("test").substring(0, 10).trim(this) + ".. ."; “测试...”
    【解决方案3】:
      function truncateString(str, length) {
         return str.length > length ? str.substring(0, length - 3) + '...' : str
      }
    

    【讨论】:

    • 如果字符串短于最大长度,则唯一不添加点的答案。并在计算中包含点...
    • 此解决方案可以处理短于最大长度的字符串,但会截断中间字。
    【解决方案4】:

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

    .truncated { display:inline-block; 
                 max-width:100px; 
                 overflow:hidden; 
                 text-overflow:ellipsis; 
                 white-space:nowrap; 
               }
    

    【讨论】:

    • 它实际上可以破坏单词,但这正是我正在寻找的。还有,漂亮的小胡子。
    • 我认为它不适用于段落中的多行文本。
    【解决方案5】:

    有原型,没有空格:

     String.prototype.trimToLength = function (trimLenght) {
        return this.length > trimLenght ? this.substring(0, trimLenght - 3) + '...' : this
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-04
      • 2011-02-16
      • 2012-01-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多