this is my attempt for truncate a string
String.prototype.truncate = function (num) {
var str = this;
if (str.length > num && num > 3 ) {
console.log(str.length);
return str.slice(0, num) + "...";
} else if (str.length > num && num <= 3) {
console.log('ok');
return str.slice(0, num) + "...";
} else {
console.log(str.length);
return str;
}
}
please any body, know how to resolve it, thanks
'Hello world!'.truncate(2) ====> 'He...'
'Hello world!'.truncate(6) ====> 'Hello...');
'Hello, world!'.truncate(6)====> 'Hello...');```
You can use String.prototype.trim() to remove extra spaces and String.prototype.replace() to replace last character if , by '' and finally add the ...
Code:
String.prototype.truncate = function(num) {
return `${this.slice(0, num).trim().replace(/\,$/, '')}...`;
}
console.log('Hello world!'.truncate(2)); // ====> 'He...'
console.log('Hello world!'.truncate(6)); // ====> 'Hello...'
console.log('Hello, world!'.truncate(6)); // ====> 'Hello...'
According to your comment:
String.prototype.truncate = function(num) {
const str = this.slice(0, num).trim().replace(/\,$/, '');
return str[str.length - 1] !== '!' ? `${str}...`: str;
}
console.log('Hello world!'.truncate(2)); // ====> 'He...'
console.log('Hello world!'.truncate(6)); // ====> 'Hello...'
console.log('Hello, world!'.truncate(6)); // ====> 'Hello...'
console.log('Hi!'.truncate(5)); // ====> 'Hi!' <---- On the comments
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With