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.
I'm going to expand on @bonbon's answer. His method is an easy way to "append N chars to an existing string", just in case anyone needs to do that. For example since "a google" is a 1 followed by 100 zeros.
NOTE: You do have to add the length of the original string to the conditional.
Here is what I use:
Convenient if you repeat yourself a lot:
For all browsers
The following function will perform a lot faster than the option suggested in the accepted answer:
You'd use it like this :
To compare the performance of this function with that of the option proposed in the accepted answer, see this Fiddle and this Fiddle for benchmarks.
For moderns browsers only
In modern browsers, you can now do this using
String.prototype.repeat
method:Read more about this method on MDN.
This option is even faster. Unfortunately, it doesn't work in any version of Internet explorer. The numbers in the table specify the first browser version that fully supports the method:
Lodash offers a similar functionality as the Javascript repeat() function which is not available in all browers. It is called _.repeat and available since version 3.0.0:
If you're not opposed to including a library in your project, lodash has a repeat function.
https://lodash.com/docs#repeat