JavaScript 在 n 个字符后修剪

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8427295/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 03:24:20  来源:igfitidea点击:

JavaScript to trim after n characters

javascriptjqueryhtmltrim

提问by testndtv

I have a HTML page which shows a Name dynamically. Now this name (FN LN) can be upto 240 charcaters. But at the UI side, I want to trim the FN/LN after about 50 characters and replace with ...

我有一个动态显示名称的 HTML 页面。现在此名称 (FN LN) 最多可包含 240 个字符。但是在 UI 方面,我想在大约 50 个字符后修剪 FN/LN 并替换为 ...

How can I do this using Javascript/jQuery

我怎样才能使用 Javascript/jQuery 做到这一点

回答by Jake Feasel

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

This should work.

这应该有效。

回答by Alec Smart

Something as simple as:

像这样简单的事情:

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

回答by PiTheNumber

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

But you can also use CSS for this: http://mattsnider.com/css/css-string-truncation-with-ellipsis/

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

回答by gion_13

here's a regex way to do that :

这是一个正则表达式方法来做到这一点:

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

Since you've asked, if you want to jqueryfy this functionality, you can make a plugin out of it :

既然你问过,如果你想 jqueryfy 这个功能,你可以用它制作一个插件:

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

And use it like this :

并像这样使用它:

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