有没有人有一个更复杂的解决方案/库,用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…");
其他回答
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>
我总是使用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插件使用。
注意,这只需要在Firefox中执行。
所有其他浏览器都支持CSS解决方案(参见支持表):
p {
white-space: nowrap;
width: 100%; /* IE6 needs any width */
overflow: hidden; /* "overflow" value must be different from visible"*/
-o-text-overflow: ellipsis; /* Opera < 11*/
text-overflow: ellipsis; /* IE, Safari (WebKit), Opera >= 11, FF > 6 */
}
具有讽刺意味的是,我从Mozilla MDC获得了该代码片段。
我在谷歌上快速搜索了一下,发现了这个……这对你有用吗?
/**
* 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
使用任一lodash的截断
_.truncate('hi-diddly-ho there, neighborino');
// → 'hi-diddly-ho there, neighbo…'
或下划线。字符串截断。
_('Hello world').truncate(5); => 'Hello...'