Skip to main content

Command Palette

Search for a command to run...

JavaScript string repeat

Published
2 min read
JavaScript string repeat
C

I'm a full-stack developer from South Africa 🇿🇦. I love writing about JavaScript, HTML and CSS.

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

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

This uses to be a tedious process making use of loops or while arrays.

Now we can simply 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 one and 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

More from this blog

D

Daily Dev Tips

887 posts

Looking to get into development? As a full-stack developer I guide you on this journey and give you bite sized tips every single day 👊