Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript truncate string without including punctuation or space

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...');```

like image 510
irkoch Avatar asked Mar 15 '26 11:03

irkoch


1 Answers

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
like image 147
Yosvel Quintero Arguelles Avatar answered Mar 17 '26 23:03

Yosvel Quintero Arguelles