lumian lumian - 7 months ago 19
Javascript Question

How to make characters in a string repeat using Javascript?

How can I make individual characters within a string repeat a given amount of times?

That is, how do I turn "XyZ" into "XXXyyyZZZ"?

Answer

Try this:

var foo = 'bar';

function makeString(str, repeat) {
  var str = Array.prototype.map.call(str, function(character) {
    var nascentStr = '';
    while (nascentStr.length < repeat) {
      nascentStr += character;
    }
    return nascentStr;
  }).join('');
  return str;
}

alert(makeString(foo, 3));

Comments