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++){
    
  }
}

6
  • Show your effort? Also don't modify builtin object (string) behavior. Commented Jan 30, 2018 at 2:10
  • i tried bu ti am stuck how to pick string from external Commented Jan 30, 2018 at 2:12
  • "Pick string from external"? What does it mean? Commented Jan 30, 2018 at 2:12
  • 'helo' a string and attach function to it and get output. i never did this before and got stuck here Commented Jan 30, 2018 at 2:13
  • 'hello'.replicate(3) Commented Jan 30, 2018 at 2:13

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.