【问题标题】:How to replace specific count of characters? [duplicate]如何替换特定的字符数? [复制]
【发布时间】:2012-09-24 11:43:36
【问题描述】:

可能重复:
smart way to shorten long strings with javascript

我有

<h1>"Very big" page title </h1>

页面标题,我需要检查字符数是否大于 30,而不是用 ... 替换最后一个字符

我可以以某种方式将文本分成两部分并替换第二部分吗?

【问题讨论】:

    标签: jquery regex replace character


    【解决方案1】:

    代码可能是这样的:

    var text = $('h1').text();
    if(text.length > 30)
       $('h1').text(text.sustring(0,30) + "...")
    

    并且不需要正则表达式。

    【讨论】:

      【解决方案2】:

      您必须使用jQuery 检查标题的长度。如果大于30,则将其拆分为指定长度,最后加上...

      Regex在这里没用。

      $('h1').each(function(){
        var text = $(this).text();
        if ( text.length > 30 ) {
          $(this).text( text.substring(0, 30) + '...' );
        }
      });
      

      【讨论】:

        猜你喜欢
        • 2022-08-07
        • 1970-01-01
        • 2012-07-20
        • 2021-07-21
        • 2012-09-04
        • 2015-09-25
        • 1970-01-01
        • 2017-03-02
        • 2020-07-26
        相关资源
        最近更新 更多