javascript 在 n 个字符后剪切一个字符串,但如果它在一个单词的中间,则剪切整个单词
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10751102/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Cut a string after n characters, but if it's in the middle of a word cut the whole word
提问by Dan Barzilay
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.
我正在尝试制作一个在 n 个字符后剪切字符串的 JS 函数 - 有效。问题是如果它在一个单词的中间看起来很糟糕,所以我需要你的帮助让它在它的中间切掉整个单词。
My code so far:
到目前为止我的代码:
if($('#desc').text().length > 505){
str = $("#desc").text();
$('#desc').text(str.substring(0, 505)).append('...');
}
P.S
聚苯乙烯
- #desc is the div that contains my string.
- you can use jQuery.
- #desc 是包含我的字符串的 div。
- 你可以使用jQuery。
回答by Bergi
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));
回答by kennebec
The lastIndexOfmethod can find the last space character in a string,
该lastIndexOf方法可以找到的最后一个空格字符的字符串,
and passing a second argument sets an upper limit.
并传递第二个参数设置上限。
var cutat= string.lastIndexOf(' ',505);
if(cutat!=-1)string=string.substring(0,cutat)+'...';
//else the string is shorter than 505 (or has no spaces...)
回答by T.J. Crowder
It's a combination of a for
loop, charAt
, and a means of testing the character against ones you consider to be word delimiters. I'll use a regular expressionfor that:
它是for
循环、charAt
和 测试字符与您认为是单词分隔符的方法的组合。我将为此使用正则表达式:
function splitString(str, index) {
var delim = /\s|[,\.]/; // Put any other character you consider
// a non-word char in the brackets.
// The initial \s is any whitespace, so
// space, tab, newline, etc.
var ch;
var i;
// Loop until we find a matching delimiter or we run out of string
for (i = index;
i >= 0 && !delim.test(str.charAt(i));
--i) {
// No body
}
if (i < 0) {
// No break before, split word in middle
return index;
}
return i + 1;
}
回答by epoch
回答by jDelforge
This simple function will work in any situation, plus adding 3 dots if needed :
这个简单的函数适用于任何情况,如果需要,还可以添加 3 个点:
function shortenString(source_string, max_length) {
var short = source_string.substr(0, max_length);
if (/^\S/.test(source_string.substr(max_length)))
return short.replace(/\s+\S*$/, "") + '...';
return short;
};
Example:
例子:
var title = "This function will work in any situation";
var short = shortenString(title, 30);
回答by Azizi
var texte = `Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc eu magna at justo bibendum accumsan. Aliquam quam metus, hendrerit eget commodo at, sagittis eu lectus. Nunc quis purus urna. Etiam sollicitudin aliquam dui, vel rutrum ligula tincidunt id. In elementum ultricies ex ut bibendum. Proin ac purus id lorem pharetra commodo. Curabitur euismod commodo eleifend. Proin porttitor aliquet massa eu dapibus. Phasellus vitae tempor nibh. Donec venenatis ligula dui, at eleifend urna facilisis sed. Proin sollicitudin vehicula mi aliquam interdum. Quisque in erat purus. Ut ut ipsum nec odio mollis maximus. Vivamus nec ultricies mi, ut posuere augue.`;
function cut(n,text) {
if(n<text.length){
while(text[n] != " " && n>0){
n--;
}
return text.substr(0,n);
}else{
return text;
}
}
document.getElementById("result").innerHTML = cut(5,texte);
<p id="result"></p>
回答by Gavriel
function cutAt(text, n) {
if(text.length > n){
for (; " .,".indexOf(text[n]) !== 0; n--){
}
return text.substr(0, n) + '...';
}
return text;
}
$('#desc').text(cutAt($('#desc').text(), 505));