2

In Python I can use:

s = "x" * 10
xxxxxxxxxx

How in JavaScript, do I create a string n characters long without a loop?

Mr Mystery Guest
  • 1,464
  • 1
  • 18
  • 47

3 Answers3

13

use String.repeat

"x".repeat(10);

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/repeat

On old browsers you could do

new Array(10).join('x')
Peter
  • 16,453
  • 8
  • 51
  • 77
  • Excellent answer, sadly it doesn't work with ExtendScript (ESTK 3.8), which is what I'm using :( – Mr Mystery Guest Jun 02 '17 at 09:49
  • Please note that you need to do Array(len + 1).join(chr) in order to get the desired number of characters. (Join adds a character between each item in the array, so it will add n-1 characters). – Yoshiyahu Dec 06 '18 at 21:32
1

Use repeat method.

'x'.repeat(10);
0
new Array(11).join('x')

For 10 x you need 11 in new Array so that 10th x is visible.

Pankaj Shukla
  • 2,657
  • 2
  • 11
  • 18