0

I want to truncate a string with a limit of characters and a condition for the last character that should be a space (this way I have no truncated words)

Example :

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 
Brahim LAMJAGUAR
  • 1,254
  • 5
  • 19
  • 28

3 Answers3

2

You can use truncate one-liner below:

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

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

console.log(truncate(sentence, 14));
Viktor Vlasenko
  • 2,332
  • 14
  • 16
1

Here's how you can truncate by words and given limit -

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
Vivek
  • 1,465
  • 14
  • 29
1

First you can have a max substring of your string, and then recursively remove the letters until you find spaces. Note that this response is made without doing monkey patching and so, not extending 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;
}
Pierre Capo
  • 1,033
  • 9
  • 23