截断包含多个字符的字符串而不会截断单词

时间:2018-07-26 15:27:50

标签: javascript truncate

我想截断一个字符串,该字符串的字符数限制为最后一个字符的条件,该条件应为空格(这样,我就没有截断的单词)

示例:

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 

3 个答案:

答案 0 :(得分:2)

您可以在下面使用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));

答案 1 :(得分:1)

在这里,您可以按单词和给定的限制截断-

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

答案 2 :(得分:1)

首先,您可以拥有字符串的最大子字符串,然后递归地删除字母,直到找到空格为止。 请注意,此响应是在没有进行猴子修补的情况下做出的,因此,不扩展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;
}