我使用此功能剪切一定长度的字符串并在末尾添加...
:
ellipsis (string, threshold) {
if (string.length > threshold) return string.substring(0, threshold) + '...'
else return string
},
用法:ellipsis(string, 35)
示例字符串:
123456789012345678901234567890123456789012345678901234567890
4567896 7890456 8904567
89456789456789456789456789456789456789456789456789456789456789
结果:
12345678901234567890123456789012...
4567896 7890456 8904567
894567...
正如你所看到的那样,第二个字符串最终变短了。
如何修改这个省略号函数,这样两个字符串即使有空格和新行也会以相同的长度结束?
修改
原文:4567896 7890456 8904567 89456789456789456789456789456789456789456789456789456789456789
替换:4567896 7890456 8904567 89456789456789456789456789456789456789456789456789456789456789
答案 0 :(得分:1)
我的Dom字符串变量没有使用replace()
新行
function ellipsis(string, threshold) {
if (string.length > threshold) {
return (string.substring(0, threshold) + '...').replace(/\\n/g,'').trim()
} else {
return string
}
}
var string1 = '123456789012345678901234567890123456789012345678901234567890';
console.log(ellipsis(string1, 35))
var string2 = '4567896 7890456 8904567 89456789456789456789456789456789456789456789456789456789456789';
console.log(ellipsis(string2, 35))
<强>更新强>
你可以扩展你的console.log
。没有任何休息