有没有人有一个更复杂的解决方案/库,用JavaScript截断字符串,并在末尾放一个省略号,比明显的一个:
if (string.length > 25) {
string = string.substring(0, 24) + "...";
}
有没有人有一个更复杂的解决方案/库,用JavaScript截断字符串,并在末尾放一个省略号,比明显的一个:
if (string.length > 25) {
string = string.substring(0, 24) + "...";
}
当前回答
这里是我的解决方案与字边界。
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);
其他回答
所有现代浏览器现在都支持一个简单的CSS解决方案,当一行文本超过可用宽度时自动添加省略号:
p {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
(请注意,这需要以某种方式限制元素的宽度,以便产生任何效果。)
基于https://css-tricks.com/snippets/css/truncate-string-with-ellipsis/。
应该注意的是,这种方法并不基于字符的数量进行限制。如果需要允许多行文本,它也不能工作。
我最近不得不这样做,最后得到:
/**
* Truncate a string over a given length and add ellipsis if necessary
* @param {string} str - string to be truncated
* @param {integer} limit - max length of the string before truncating
* @return {string} truncated string
*/
function truncate(str, limit) {
return (str.length < limit) ? str : str.substring(0, limit).replace(/\w{3}$/gi, '...');
}
对我来说感觉很好很干净:)
最好的函数。归功于文本省略。
function textEllipsis(str, maxLength, { side = "end", ellipsis = "..." } = {}) {
if (str.length > maxLength) {
switch (side) {
case "start":
return ellipsis + str.slice(-(maxLength - ellipsis.length));
case "end":
default:
return str.slice(0, maxLength - ellipsis.length) + ellipsis;
}
}
return str;
}
例子:
var short = textEllipsis('a very long text', 10);
console.log(short);
// "a very ..."
var short = textEllipsis('a very long text', 10, { side: 'start' });
console.log(short);
// "...ng text"
var short = textEllipsis('a very long text', 10, { textEllipsis: ' END' });
console.log(short);
// "a very END"
我在谷歌上快速搜索了一下,发现了这个……这对你有用吗?
/**
* 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>