有没有人有一个更复杂的解决方案/库,用JavaScript截断字符串,并在末尾放一个省略号,比明显的一个:
if (string.length > 25) {
string = string.substring(0, 24) + "...";
}
有没有人有一个更复杂的解决方案/库,用JavaScript截断字符串,并在末尾放一个省略号,比明显的一个:
if (string.length > 25) {
string = string.substring(0, 24) + "...";
}
当前回答
如果使用Ext.js,可以使用Ext.util.Format.ellipsis函数。
其他回答
该功能还可以截断空格和文字部分。(例如:母亲变成飞蛾……)
String.prototype.truc= function (length) {
return this.length>length ? this.substring(0, length) + '…' : this;
};
用法:
"this is long length text".trunc(10);
"1234567890".trunc(5);
输出:
这是… 12345年……
大多数现代Javascript框架(JQuery, Prototype等)都有一个附加在String上的实用函数来处理这个问题。
下面是Prototype中的一个例子:
'Some random text'.truncate(10);
// -> 'Some ra...'
这似乎是您希望其他人处理/维护的功能之一。我会让框架来处理它,而不是编写更多的代码。
('long text to be truncated').replace(/(.{250})..+/, "$1…");
不知何故,上面的代码是不工作的某种复制粘贴或书面文本在vuejs应用程序。所以我使用lodash截断,它现在工作正常。
_.truncate('long text to be truncated', { 'length': 250, 'separator': ' '});
我喜欢使用.slice(),第一个参数是开始索引,第二个是结束索引。介于两者之间的都是你能得到的。
var long = "hello there! Good day to ya."
// hello there! Good day to ya.
var short = long.slice(0, 5)
// hello
所有现代浏览器现在都支持一个简单的CSS解决方案,当一行文本超过可用宽度时自动添加省略号:
p {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
(请注意,这需要以某种方式限制元素的宽度,以便产生任何效果。)
基于https://css-tricks.com/snippets/css/truncate-string-with-ellipsis/。
应该注意的是,这种方法并不基于字符的数量进行限制。如果需要允许多行文本,它也不能工作。