jQuery 如何在 X 个字符后剪切字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18146354/
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-08-26 21:06:41  来源:igfitidea点击:

How can I cut a string after X characters?

javascriptjquery

提问by Michael Unterthurner

How can I cut a string after a specific number of characters in JavaScript?

如何在 JavaScript 中的特定数量的字符后剪切字符串?

I then want to append the '…' Unicode character. How can I do this?

然后我想附加 '...' Unicode 字符。我怎样才能做到这一点?

回答by Alex K.

Simply

简单地

  var trunc = "abcdef".substr(0, 3) + "\u2026";

回答by mohammedn

var trucatedText = yourtext.substring(0, 3) + '...';  // substring(from, to);

回答by Steve Brush

The other answers are great, but they always add an ellipsis. The following will only add an ellipsis if the string is too long:

其他答案很好,但它们总是添加省略号。如果字符串太长,以下只会添加省略号:

function truncateText(text, length) {
  if (text.length <= length) {
    return text;
  }

  return text.substr(0, length) + '\u2026'
}

let truncated;
truncated = truncateText('Hello, World!', 10);
console.log(truncated);
truncated = truncateText('Hello, World!', 50);
console.log(truncated);

回答by Kamil Szymański

Sth like this?

这样的?

var text= "This is your text";
var stripHere = 7;
var shortText = text.substring(0, stripHere) + "...";

alert(shortText);

http://jsfiddle.net/ThKsw/

http://jsfiddle.net/ThKsw/