有没有人有一个更复杂的解决方案/库,用JavaScript截断字符串,并在末尾放一个省略号,比明显的一个:
if (string.length > 25) {
string = string.substring(0, 24) + "...";
}
有没有人有一个更复杂的解决方案/库,用JavaScript截断字符串,并在末尾放一个省略号,比明显的一个:
if (string.length > 25) {
string = string.substring(0, 24) + "...";
}
当前回答
使用以下代码
function trancateTitle (title) {
var length = 10;
if (title.length > length) {
title = title.substring(0, length)+'...';
}
return title;
}
其他回答
我对Kooilnc的解决方案投了赞成票。非常好的紧凑解决方案。有一个小的边缘情况,我想解决。如果有人出于某种原因输入了一个很长的字符序列,它不会被截断:
function truncate(str, n, useWordBoundary) {
var singular, tooLong = str.length > n;
useWordBoundary = useWordBoundary || true;
// Edge case where someone enters a ridiculously long string.
str = tooLong ? str.substr(0, n-1) : str;
singular = (str.search(/\s/) === -1) ? true : false;
if(!singular) {
str = useWordBoundary && tooLong ? str.substr(0, str.lastIndexOf(' ')) : str;
}
return tooLong ? str + '…' : str;
}
这里是我的解决方案与字边界。
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);
我在谷歌上快速搜索了一下,发现了这个……这对你有用吗?
/**
* 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
本质上,检查给定字符串的长度。如果它比给定的长度n长,剪辑到长度n (substr或slice),并添加html实体…(…)到剪短的字符串。
这样的方法看起来像
function truncate(str, n){
return (str.length > n) ? str.slice(0, n-1) + '…' : str;
};
如果你所说的“更复杂”是指在字符串的最后一个单词边界处截断,那么你需要额外的检查。 首先将字符串剪辑到所需的长度,然后将其结果剪辑到最后一个单词边界
function truncate( str, n, useWordBoundary ){
if (str.length <= n) { return str; }
const subString = str.slice(0, n-1); // the original check
return (useWordBoundary
? subString.slice(0, subString.lastIndexOf(" "))
: subString) + "…";
};
您可以用您的函数扩展本机String原型。在这种情况下,str形参应该被删除,函数中的str应该被替换为:
String.prototype.truncate = String.prototype.truncate ||
function ( n, useWordBoundary ){
if (this.length <= n) { return this; }
const subString = this.slice(0, n-1); // the original check
return (useWordBoundary
? subString.slice(0, subString.lastIndexOf(" "))
: subString) + "…";
};
更教条的开发人员可能会因此强烈地责备你(“不要修改你不拥有的对象”)。不过我不介意)。
一种不扩展String原型的方法是创建 您自己的helper对象,包含您提供的(长)字符串 和前面提到的截断方法。这就是代码片段 下面。
const LongstringHelper = str => { const sliceBoundary = str => str.substr(0, str.lastIndexOf(" ")); const truncate = (n, useWordBoundary) => str.length <= n ? str : `${ useWordBoundary ? sliceBoundary(str.slice(0, n - 1)) : str.slice(0, n - 1)}…`; return { full: str, truncate }; }; const longStr = LongstringHelper(`Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum`); const plain = document.querySelector("#resultTruncatedPlain"); const lastWord = document.querySelector("#resultTruncatedBoundary"); plain.innerHTML = longStr.truncate(+plain.dataset.truncateat, !!+plain.dataset.onword); lastWord.innerHTML = longStr.truncate(+lastWord.dataset.truncateat, !!+lastWord.dataset.onword); document.querySelector("#resultFull").innerHTML = longStr.full; body { font: normal 12px/15px verdana, arial; } p { width: 450px; } #resultTruncatedPlain:before { content: 'Truncated (plain) n='attr(data-truncateat)': '; color: green; } #resultTruncatedBoundary:before { content: 'Truncated (last whole word) n='attr(data-truncateat)': '; color: green; } #resultFull:before { content: 'Full: '; color: green; } <p id="resultTruncatedPlain" data-truncateat="120" data-onword="0"></p> <p id="resultTruncatedBoundary" data-truncateat="120" data-onword="1"></p> <p id="resultFull"></p>
最后,您可以使用css仅截断HTML节点中的长字符串。它给你较少的控制,但可能是可行的解决方案。
body { font: normal 12px/15px verdana, arial; margin: 2rem; } .truncate { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; width: 30vw; } .truncate:before{ content: attr(data-longstring); } .truncate:hover::before { content: attr(data-longstring); width: auto; height: auto; overflow: initial; text-overflow: initial; white-space: initial; background-color: white; display: inline-block; } <div class="truncate" data-longstring="Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."></div>
有时文件名是编号的,其中索引可能在开头或结尾。所以我想从弦的中心开始缩短:
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个字节的填充字符。