在 n 个字符之后剪一个字符串,但如果它在一个单词的中间,则剪掉整个单词

Cut a string after n characters, but if it's in the middle of a word cut the whole word

本文关键字:一个 单词 中间 字符串 字符 之后 如果      更新时间:2023-09-26

我正在尝试制作一个JS函数,该函数在n个字符之后剪切字符串 - 这有效。问题是,如果它在一个单词的中间,它看起来很糟糕,所以我需要你的帮助,让它在中间剪掉整个单词。

到目前为止我的代码:

if($('#desc').text().length > 505){
  str = $("#desc").text();
  $('#desc').text(str.substring(0, 505)).append('...');
}

附言

  • #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));

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...)
它是

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;
}

现场示例 | 来源

你可能想看看Cutter.js

Cutter.js 是一个用于截断 HTML 代码以限制其 长度,按字数,而不会丢失标记。

这个简单的函数在任何情况下都可以工作,如果需要,还可以添加 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;
};

例:

var title = "This function will work in any situation";
var short = shortenString(title, 30);

		
    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>

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));