-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
  • 32,084
  • 8
  • 49
  • 92
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
  • 1,876
  • 2
  • 17
  • 24