Search code examples
javascriptstringloopsmultiplication

Manipulating a String's content with an Integer


I'f you're familiar with Python, I'm sure you're aware that you can multiply a String by an Integer to get that desired amount of Strings back.


Example:

'J' * 3 --> 'JJJ'

What's the most efficient way to do this in JavaScript?

I was looking for an inline method; similar to that of Pythons behaviour


A few of my ideas:

var str = 'J',
    strOld = str,
    timesToExtend = 3;

for(var i = 0; i < timesToExtend; i++){
    str += strOld;
}

= 'JJJ'

var str = 'J',
    timesToExtend = 5,
    strOld = str;

while(!timesToExtend){
  str += strOld;
  timesToExtend--;
}

These are just rough ideas, so don't expect them to be 100% accurate and working. I assume this MUST contain a loop; however any method without a loop will be praised!

Thanks for reading; thank you for your response in advance!


Solution

  • In ES6 you can use Array.prototype.fill() and then join the array:

    Array(3).fill('J').join('');