截断具有多个字符的字符串而不截断单词

Truncated a string with a number of characters without truncating words

我想截断一个字符串,其字符数限制和最后一个字符的条件应该是 space(这样我就没有截断的词)

示例:

var sentence = "The string that I want to truncate!";
sentence.methodToTruncate(14); // 14 is the limit of max characters 
console.log("Truncated result : " + sentence); // Truncated result : The string 

这是按字数和给定限制截断的方法 -

String.prototype.methodToTruncate = function(n) {
    var parts = this.split(" ");
    var result = "";
    var i = 0;
    while(result.length >= n || i < parts.length) {
       if (result.length + parts[i].length > n) {
           break;
       }
       
       result += " " + parts[i];
       i++;
    }
    
    return result;
}

var sentence = "The string that I want to truncate!";
console.log("Truncated result : " + sentence.methodToTruncate(14)); // Truncated result : The string

首先你可以得到你的字符串的最大子串,然后递归地删除字母直到找到空格。 请注意,此响应是在没有进行猴子修补的情况下做出的,因此没有扩展 String.prototype :

var sentence = "Hello a";
var a = methodToTruncate(sentence, 5); // 14 is the limit of max characters 
console.log("Truncated result : " + a); // Truncated result : The string 

function methodToTruncate(str, num) {

 if(num>= str.length){ return str;}
  var res = str.substring(0, num);
  
  while (str[res.length] != " " && res.length != 0) {
    console.log(res.length)
    res = res.substring(0, res.length-1);
  }
  return res;
}

您可以使用下面的truncate一行:

const sentence = "The string that I want to truncate!";

const truncate = (str, len) => str.substring(0, (str + ' ').lastIndexOf(' ', len));

console.log(truncate(sentence, 14));