Dan*_*lay 12 javascript jquery truncate character
我正在尝试创建一个在n个字符后剪切字符串的JS函数 - 这是有效的.问题是,如果它在一个单词的中间看起来很糟糕,所以我需要你的帮助,如果它是它的中间,它会切断整个单词.
我的代码到目前为止:
if($('#desc').text().length > 505){
str = $("#desc").text();
$('#desc').text(str.substring(0, 505)).append('...');
}
Run Code Online (Sandbox Code Playgroud)
PS
Ber*_*rgi 18
function cut(n) {
return function textCutter(i, text) {
var short = text.substr(0, n);
if (/^\S/.test(text.substr(n)))
return short.replace(/\s+\S*$/, "");
return short;
};
}
$('#desc').text(cut(505));
Run Code Online (Sandbox Code Playgroud)
该lastIndexOf方法可以找到字符串中的最后一个空格字符,
并传递第二个参数设置上限.
var cutat= string.lastIndexOf(' ',505);
if(cutat!=-1)string=string.substring(0,cutat)+'...';
//else the string is shorter than 505 (or has no spaces...)
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
16485 次 |
最近记录: |