代码之家  ›  专栏  ›  技术社区  ›  Reece

修剪字符串宽度jQuery[重复]

  •  -1
  • Reece  · 技术社区  · 8 年前

    如何修剪字符串宽度,使其不超过20个字符,包括空格和。。。到绳子的末端?

    <p class="streetname">Galloway Road, Bishop's Stortford</p>
    

    2 回复  |  直到 8 年前
        1
  •  0
  •   Ankit Agarwal    8 年前

    你可以用 substr()

    var text = $('.streetname').text();
    var newText = text.substr(0,17) + '...';
    $('.streetname').text(newText)
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <p class="streetname">Galloway Road, Bishop's Stortford</p>
        2
  •  0
  •   Christopher Supertramp    8 年前

    您可以这样做:

    if ($(".streetname").text().length > 20) {         
        $(".streetname").text($(".streetname").text().substring(0,50) + '...');
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <p class="streetname">This text is way to long to be displayed on the site so we just short it with jquery</p>