Search code examples
javascriptstringprototype

Add a function to String class using JavaScript's String.prototype


I have to create a function to be added to the string class. For example "hi".exclamify(3) should return hi with three !!! at the end of the string. I know I have to make use of

String.prototype.exclamify = function(n) 
{
  // Function definition goes here
  console.log(this);
}
"hi".exclamify(2);

When I call the function as "hi".exclamify(2); the console returns [String: 'Hello'], what to do to get only the value of the string which is "Hello"? I used Object.values(this) which returned [ 'H', 'e', 'l', 'l', 'o' ]. I want the exact string to implement the function.


Solution

  • It looks like the value of this was working for you and contained the correct string. Here's a quick try at your problem:

    String.prototype.exclamify=function(n){ return `${this}${'!'.repeat(n)}` }
    
    const testString = "hello";
    
    console.log(testString.exclamify(3));
    console.log(testString.exclamify(5));