有没有人有一个更复杂的解决方案/库,用JavaScript截断字符串,并在末尾放一个省略号,比明显的一个:
if (string.length > 25) {
string = string.substring(0, 24) + "...";
}
有没有人有一个更复杂的解决方案/库,用JavaScript截断字符串,并在末尾放一个省略号,比明显的一个:
if (string.length > 25) {
string = string.substring(0, 24) + "...";
}
当前回答
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>
其他回答
使用以下代码
function trancateTitle (title) {
var length = 10;
if (title.length > length) {
title = title.substring(0, length)+'...';
}
return title;
}
我喜欢使用.slice(),第一个参数是开始索引,第二个是结束索引。介于两者之间的都是你能得到的。
var long = "hello there! Good day to ya."
// hello there! Good day to ya.
var short = long.slice(0, 5)
// hello
我总是使用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插件使用。
以下是我的解决方案,与其他建议相比有一些改进:
String.prototype.truncate = function(){
var re = this.match(/^.{0,25}[\S]*/);
var l = re[0].length;
var re = re[0].replace(/\s$/,'');
if(l < this.length)
re = re + "…";
return re;
}
// "This is a short string".truncate();
"This is a short string"
// "Thisstringismuchlongerthan25characters".truncate();
"Thisstringismuchlongerthan25characters"
// "This string is much longer than 25 characters and has spaces".truncate();
"This string is much longer…"
It:
在25之后的第一个空格上截断 字符 扩展JavaScript字符串对象, 因此它可以用于(并链接到) 任何字符串。 如果截断将修剪字符串 结果在一个尾随空间中; 是否添加unicode hellip实体 (省略号)如果截断的字符串长于25个字符
大多数现代Javascript框架(JQuery, Prototype等)都有一个附加在String上的实用函数来处理这个问题。
下面是Prototype中的一个例子:
'Some random text'.truncate(10);
// -> 'Some ra...'
这似乎是您希望其他人处理/维护的功能之一。我会让框架来处理它,而不是编写更多的代码。