如何在 JavaScript 中特定数量的字符后剪切字符串?
然后我想附加 '...' Unicode 字符。我怎样才能做到这一点?
简单地
var trunc = "abcdef".substr(0, 3) + "\u2026";
其他答案很好,但他们总是添加省略号。如果字符串太长,以下只会添加省略号:
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);
var trucatedText = yourtext.substring(0, 3) + '...'; // substring(from, to);
像这样吗?
var text= "This is your text";
var stripHere = 7;
var shortText = text.substring(0, stripHere) + "...";
alert(shortText);