在n个字符后剪切一个字符串,但如果它在一个单词的中间剪切整个单词 [英] Cut a string after n characters, but if it's in the middle of a word cut the whole word
本文介绍了在n个字符后剪切一个字符串,但如果它在一个单词的中间剪切整个单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图做一个JS函数,在n个字符后剪切一个字符串 - 这是工作。问题是如果它在一个单词的中间它看起来不好,所以我需要你的帮助,使它削减整个单词,如果它是中间。
I'm trying to make a JS function that cuts a string after n characters - that works. The problem is if it's in the middle of a word it looks bad, so I need your help making it cut the whole word if it's the middle of it.
我的代码到目前为止:
if($('#desc').text().length > 505){
str = $("#desc").text();
$('#desc').text(str.substring(0, 505)).append('...');
}
PS
- #desc是包含我的字符串的div。
- 您可以使用jQuery。
推荐答案
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));
这篇关于在n个字符后剪切一个字符串,但如果它在一个单词的中间剪切整个单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文