-1

I wrote my function like this: truncate('Hello world!, 5);

But I want write my function like this: 'Hello world!'.truncate(5);

function truncate(str, num) {
  if (str.length <= num) {
  return str
}
return str.slice(0, num) + '...'

}

console.log(truncate('Hello world!', 5))
Mitya
  • 33,629
  • 9
  • 60
  • 107
Tiguere
  • 3
  • 1

1 Answers1

1

Use prototype object to extend methods.

String.prototype.truncate = function(num){
    if (this.toString().length <= num) return this.toString();
    return this.toString().slice(0,num)
};
'Hello World!'.truncate(5); //  Hello
Gavin
  • 2,214
  • 2
  • 18
  • 26