有没有人有一个更复杂的解决方案/库,用JavaScript截断字符串,并在末尾放一个省略号,比明显的一个:
if (string.length > 25) {
string = string.substring(0, 24) + "...";
}
有没有人有一个更复杂的解决方案/库,用JavaScript截断字符串,并在末尾放一个省略号,比明显的一个:
if (string.length > 25) {
string = string.substring(0, 24) + "...";
}
当前回答
如果你想用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;
}
其他回答
Text-overflow:省略号是您需要的属性。有了这个和一个溢出:隐藏在一个特定的宽度,超过它的所有东西将在最后得到三个周期的效果……不要忘记添加空格:nowrap或文本将被放入多行。
.wrap{
text-overflow: ellipsis
white-space: nowrap;
overflow: hidden;
width:"your desired width";
}
<p class="wrap">The string to be cut</p>
聪明的地方: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))
我在谷歌上快速搜索了一下,发现了这个……这对你有用吗?
/**
* 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>
所有现代浏览器现在都支持一个简单的CSS解决方案,当一行文本超过可用宽度时自动添加省略号:
p {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
(请注意,这需要以某种方式限制元素的宽度,以便产生任何效果。)
基于https://css-tricks.com/snippets/css/truncate-string-with-ellipsis/。
应该注意的是,这种方法并不基于字符的数量进行限制。如果需要允许多行文本,它也不能工作。