Cut a string after n characters, but if it's i

2019-04-20 07:24发布

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.

7条回答
仙女界的扛把子
2楼-- · 2019-04-20 07:48
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));
查看更多
相关推荐>>
3楼-- · 2019-04-20 07:52
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));
查看更多
啃猪蹄的小仙女
4楼-- · 2019-04-20 07:56

		
    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>

查看更多
啃猪蹄的小仙女
5楼-- · 2019-04-20 07:59

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.

查看更多
【Aperson】
6楼-- · 2019-04-20 08:02

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);
查看更多
来,给爷笑一个
7楼-- · 2019-04-20 08:08

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

查看更多
登录 后发表回答