JavaScript string repeat

โœ๏ธ

Repeating string is super easy in Vanilla JavaScript these days, learn how!

10 Jan, 2021 ยท 1 min read

Did you know JavaScript comes with a handy repeat() function?

It allows us to repeat a string an x number of times.

This used to be a tedious process using loops or while arrays.

Now we can call repeat() on a string.

Making use of JavaScript string.repeat()

As mentioned, you can call this function on a string, and it will repeat it an x number of times.

This x is the only argument it takes.

'two'.repeat(2);
// 'twotwo'

This makes it far clearer for the code to state a string is repeated two times.

Old-school, you might have found yourself doing something like this.

let output = '';
for (i = 0; i < 2; i++) {
  output += 'two';
}

As you can see a more tedious process. (There are some alternatives, but nothing as simple as calling repeat()).

Browser support

The browser support for the string.repeat is pretty good. Only IE can't deal with it.

String repeat browser support

Thank you for reading, and let's connect!

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter

Spread the knowledge with fellow developers on Twitter
Tweet this tip
Powered by Webmentions - Learn more

Read next ๐Ÿ“–

JavaScript sending data between windows

9 Sep, 2022 ยท 4 min read

JavaScript sending data between windows

Using the native payment request JavaScript API

9 Aug, 2022 ยท 8 min read

Using the native payment request JavaScript API