Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Repeat a string in JavaScript a number of times

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.

like image 398
Steve Avatar asked Dec 09 '09 22:12

Steve


People also ask

How do you repeat a string in JavaScript?

JavaScript String repeat() The repeat() method returns a string with a number of copies of a string. The repeat() method returns a new string. The repeat() method does not change the original string.

Can you multiply a string in JavaScript?

There are three ways you can multiply the string above: Using the String. repeat() method. Using a for loop.

What is repetition JavaScript?

Repetition means Loopingwrite("Here's a line of output. <br />"); document.


Video Answer


1 Answers

These days, the repeat string method is implemented almost everywhere. (It is not in Internet Explorer.) So unless you need to support older browsers, you can simply write:

"a".repeat(10) 

Before repeat, we used this hack:

Array(11).join("a") // create string with 10 a's: "aaaaaaaaaa" 

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

Simon also points out that according to this benchmark, it appears that it's faster in Safari and Chrome (but not Firefox) to repeat a character multiple times by simply appending using a for loop (although a bit less concise).

like image 115
Jason Orendorff Avatar answered Oct 09 '22 13:10

Jason Orendorff