问题
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.
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.
回答1:
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));
回答2:
The lastIndexOf method can find the last space character in a string,
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...)
回答3:
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 expression for that:
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;
}
Live example | source
回答4:
You may want to have a look at Cutter.js
Cutter.js is a library used for truncating HTML code to limit its length, by word number, without losing the markup.
回答5:
This simple function will work in any situation, plus adding 3 dots if needed :
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);
回答6:
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>
回答7:
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));
来源:https://stackoverflow.com/questions/10751102/cut-a-string-after-n-characters-but-if-its-in-the-middle-of-a-word-cut-the-who