0

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!

2
  • Thanks for the edit! Commented Aug 12, 2016 at 22:43
  • stackoverflow.com/questions/14343844/… Commented Aug 12, 2016 at 22:47

1 Answer 1

0

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

Array(3).fill('J').join('');
Sign up to request clarification or add additional context in comments.

2 Comments

Will this work in Node.JS?
@Robinlemon it works from node 4.4.5