有没有人有一个更复杂的解决方案/库,用JavaScript截断字符串,并在末尾放一个省略号,比明显的一个:
if (string.length > 25) {
string = string.substring(0, 24) + "...";
}
有没有人有一个更复杂的解决方案/库,用JavaScript截断字符串,并在末尾放一个省略号,比明显的一个:
if (string.length > 25) {
string = string.substring(0, 24) + "...";
}
当前回答
我总是使用cutr .js库来截断字符串并添加自定义省略号:
new Cuttr('.container', { 此处的选项 截断:“单词”, 长度: 8, 结尾:“...►' }); <script src=“https://unpkg.com/cuttr@1.1.1/dist/cuttr.min.js”></script> <p class=“container”>Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.在vero eos et accusam et justo duo dolores et ea rebum.Stet clita kasd gubergren, no sea takimata sanctus est lorem ipsum dolor sit amet.</p>
这是迄今为止我所知道的用JS切割字符串的最简单的方法(并且没有任何依赖关系),它也可以作为jQuery插件使用。
其他回答
这里是我的解决方案与字边界。
let s = "At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat." let s_split = s.split(/\s+/); let word_count = 0; let result = ""; //1 for(let i = 0; word_count < 100; i++){ word_count += s_split[i].length+1; result += (s_split[i] + " "); } console.log(result); // 2 word_count = 0; result = s_split.reduce((x,y)=>{ word_count+=(y.length+1); if(word_count>=100) return x; else return x+" "+y;}, "").substring(1); console.log(result);
人们希望用JavaScript而不是CSS来实现这一点是有充分理由的。
在JavaScript中截断为8个字符(包括省略号):
short = long.replace(/(.{7})..+/, "$1…");
or
short = long.replace(/(.{7})..+/, "$1…");
如果你想用css而不是JavaScript;
.textShortDesc { /*Here we have determined the max number of lines.*/
display: block; /* or inline-block */
-o-text-overflow: ellipsis; /* Opera < 11*/
text-overflow: ellipsis; /* IE, Safari (WebKit), Opera >= 11, FF > 6 */
word-wrap: break-word;
overflow: hidden;
max-height: 2em; /*max-height/line-height=rowCount */
line-height: 1em;
}
我在谷歌上快速搜索了一下,发现了这个……这对你有用吗?
/**
* Truncate a string to the given length, breaking at word boundaries and adding an elipsis
* @param string str String to be truncated
* @param integer limit Max length of the string
* @return string
*/
var truncate = function (str, limit) {
var bits, i;
if (STR !== typeof str) {
return '';
}
bits = str.split('');
if (bits.length > limit) {
for (i = bits.length - 1; i > -1; --i) {
if (i > limit) {
bits.length = i;
}
else if (' ' === bits[i]) {
bits.length = i;
break;
}
}
bits.push('...');
}
return bits.join('');
};
// END: truncate
聪明的地方: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))