有没有人有一个更复杂的解决方案/库,用JavaScript截断字符串,并在末尾放一个省略号,比明显的一个:
if (string.length > 25) {
string = string.substring(0, 24) + "...";
}
有没有人有一个更复杂的解决方案/库,用JavaScript截断字符串,并在末尾放一个省略号,比明显的一个:
if (string.length > 25) {
string = string.substring(0, 24) + "...";
}
当前回答
在我看来,C_harm的答案是最好的。请注意,如果你想使用
"My string".truncate(n)
您将不得不使用regexp对象构造函数而不是文字。此外,在转换\S时还必须转义它。
String.prototype.truncate =
function(n){
var p = new RegExp("^.{0," + n + "}[\\S]*", 'g');
var re = this.match(p);
var l = re[0].length;
var re = re[0].replace(/\s$/,'');
if (l < this.length) return re + '…';
};
其他回答
在我看来,C_harm的答案是最好的。请注意,如果你想使用
"My string".truncate(n)
您将不得不使用regexp对象构造函数而不是文字。此外,在转换\S时还必须转义它。
String.prototype.truncate =
function(n){
var p = new RegExp("^.{0," + n + "}[\\S]*", 'g');
var re = this.match(p);
var l = re[0].length;
var re = re[0].replace(/\s$/,'');
if (l < this.length) return re + '…';
};
有时文件名是编号的,其中索引可能在开头或结尾。所以我想从弦的中心开始缩短:
function stringTruncateFromCenter(str, maxLength) {
const midChar = "…"; // character to insert into the center of the result
var left, right;
if (str.length <= maxLength) return str;
// length of beginning part
left = Math.ceil(maxLength / 2);
// start index of ending part
right = str.length - Math.floor(maxLength / 2) + 1;
return str.substr(0, left) + midChar + str.substring(right);
}
请注意,我在这里使用了UTF-8中超过1个字节的填充字符。
该功能还可以截断空格和文字部分。(例如:母亲变成飞蛾……)
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年……
聪明的地方:D
//My Huge Huge String let tooHugeToHandle = `It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).` //Trim Max Length const maxValue = 50 // The barber. const TrimMyString = (string, maxLength, start = 0) => { //Note - `start` is if I want to start after some point of the string if (string.length > maxLength) { let trimmedString = string.substr(start, maxLength) return ( trimmedString.substr( start, Math.min(trimmedString.length, trimmedString.lastIndexOf(' ')) ) + ' ...' ) } return string } console.log(TrimMyString(tooHugeToHandle, maxValue))
大多数现代Javascript框架(JQuery, Prototype等)都有一个附加在String上的实用函数来处理这个问题。
下面是Prototype中的一个例子:
'Some random text'.truncate(10);
// -> 'Some ra...'
这似乎是您希望其他人处理/维护的功能之一。我会让框架来处理它,而不是编写更多的代码。