Reputation: 1344
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
Upvotes: 0
Views: 1291
Reputation: 1053
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;
}
Upvotes: 1
Reputation: 2512
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));
Upvotes: 2
Reputation: 1513
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
Upvotes: 1