0

Today i was asked question in interview. when i call 'hello'.replicate(3) it should print 'hellohellohello'

please help if anyone has answer to this

// 'hello'.replicate(3)
//output > 'hellohellohello'


function replicate(num){
  for(i=0; i<3; i++){
    
  }
}
Jay
  • 375
  • 2
  • 5
  • 17

1 Answers1

2

A JavaScript string will inherit functions from its prototype, so you need to add the function to the string prototype. For example:

String.prototype.replicate = function (n) {
  var replicatedString = '';

  for (var i = 0; i < n; i++) {
    replicatedString += this;
  }

  return replicatedString;
};

See also:

javascript: add method to string class

Andrew
  • 362
  • 3
  • 8