tags:

views:

246

answers:

2

In Perl I can repeat a character multiple times using the syntax:

$a = "a" x 10; // results in "aaaaaaaaaa"

Is there a simple way to accomplish this in Javascript? I can obviously use a function, but I was wondering if there was any built in approach, or some other clever technique.

Thanks

+19  A: 
Array(11).join("a")

(Note that an array of length 11 gets you only 10 "a"s, since Array.join puts the argument between the array elements.)

Jason Orendorff
thats the clever technique ;-)
medopal
Note that ironically, such code is longer than a simple string of 10 'a' characters. :P (But for larger lengths it would be more efficient. :P)
Amber
+1, I use the same technique in a Windows Sidebar Gadget to create a new zip file using a string of 15xString.fromCharCode(00). Array(16).join(String.fromCharCode(00)) is so much easier.
Andy E
Yup, that's the clever technique I was looking for. Thanks.
Steve
+1  A: 

// Same idea, convenient if you repeat yourself a lot:

String.prototype.repeat= function(n){
    n= n || 1;
    return Array(n+1).join(this);
}

alert('Are we there yet?\nNo.\n'.repeat(10))

kennebec