有没有人有一个更复杂的解决方案/库,用JavaScript截断字符串,并在末尾放一个省略号,比明显的一个:
if (string.length > 25) {
string = string.substring(0, 24) + "...";
}
有没有人有一个更复杂的解决方案/库,用JavaScript截断字符串,并在末尾放一个省略号,比明显的一个:
if (string.length > 25) {
string = string.substring(0, 24) + "...";
}
当前回答
人们希望用JavaScript而不是CSS来实现这一点是有充分理由的。
在JavaScript中截断为8个字符(包括省略号):
short = long.replace(/(.{7})..+/, "$1…");
or
short = long.replace(/(.{7})..+/, "$1…");
其他回答
聪明的地方: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))
如果使用Ext.js,可以使用Ext.util.Format.ellipsis函数。
在我看来,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 + '…';
};
人们希望用JavaScript而不是CSS来实现这一点是有充分理由的。
在JavaScript中截断为8个字符(包括省略号):
short = long.replace(/(.{7})..+/, "$1…");
or
short = long.replace(/(.{7})..+/, "$1…");
我不确定这是否算聪明,但它简洁明了:
truncateStringToLength (string, length) {
return (string.length > length)
? `${string.substring(0, length)} …`
: string
}
……然后:
truncateStringToLength('Lorem ipsum dolor sit amet, consetetur sadipscing', 20)