【问题标题】:Display begin and end of string (jquery) [duplicate]显示字符串的开头和结尾(jquery)[重复]
【发布时间】:2018-08-05 08:35:40
【问题描述】:

我有子字符串的功能:

$('#text').on('mouseup', function(e){ 
    var text = "There are a lot of text";
    if (text != '') {
        $('.ppr .sel_text').text(text.trim().substr(0,21) + "..."); 
    }
});

我怎样才能只得到文本字符串的开头结尾?

例如,现在的结果是“There are a lot of te...”。

我想得到:“有...文本”

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    String.prototype.substr()

    警告:虽然 String.prototype.substr(...) 并未严格弃用(如“从 Web 标准中删除”),但它在 ECMA-262 标准的附件 B 中定义,其介绍指出:


    … 本附件中规定的所有语言特性和行为都有一个或多个不受欢迎的特性,在没有遗留使用的情况下,将从本规范中删除。 … … 程序员在编写新的 ECMAScript 代码时不应使用或假设存在这些特性和行为。 …

    请改用String.prototype.substring()。您必须从开头和结尾获取字符串。您可以尝试以下方式:

    $('#text').on('mouseover', function(e){ 
      var text = "There are a lot of text";
      if (text != '') {
        $('.sel_text').text(text.substring(0,10) + "..." + text.trim().substring(text.length - 5));
      }
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div id="text">There are a lot of text<div>
    <div class="sel_text"></div>

    【讨论】:

      猜你喜欢
      • 2012-10-27
      • 2021-02-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多