在n个字符后修剪的JavaScript

时间:2011-12-08 06:55:13

标签: javascript jquery html trim

我有一个动态显示名称的HTML页面。现在这个名字(FN LN)可以达到240个charcaters。但是在UI方面,我希望在大约50个字符后修剪FN / LN并替换为...

如何使用Javascript / jQuery

执行此操作

4 个答案:

答案 0 :(得分:16)

$("#FN, #LN").each (function () {
  if ($(this).text().length > 50)
    $(this).text($(this).text().substring(0,50) + '...');
});

这应该有用。

答案 1 :(得分:6)

简单的事情:

if (name.length > 50) {
    name = name.substr(0,50)+'...';
}

答案 2 :(得分:3)

if ($('#name').text().length > 50)
{
    $('#name').text( $('#name').text().substring(0,50)+"..." );
}

但您也可以使用CSS:http://mattsnider.com/css/css-string-truncation-with-ellipsis/

答案 3 :(得分:3)

这是一种正则表达式:

text.replace(/(^.{50}).*$/,'$1...');  

因为你曾经问过,如果你想要jqueryfy这个功能,你可以用它来制作一个插件:

$.fn.trimAfter(n,replacement){
    replacement = replacement || "...";
    return this.each(function(i,el){
        $(el).text($(el).text().substring(n) + replacement);
    });
}

并像这样使用它:

$("#FN, #LN").trimAfter(50,'...');