17

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

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

4

4 回答 4

26

简单地

  var trunc = "abcdef".substr(0, 3) + "\u2026";
于 2013-08-09T12:14:30.303 回答
9

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

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);

于 2018-07-12T13:32:14.323 回答
6
var trucatedText = yourtext.substring(0, 3) + '...';  // substring(from, to);
于 2013-08-09T12:16:30.050 回答
1

像这样吗?

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

alert(shortText);

http://jsfiddle.net/ThKsw/

于 2013-08-09T12:18:22.427 回答