How to repeat a string the with String repeat() Method – JavaScript

The method repeat() is basically a string method that repeats a string as many times as you need. And the syntax looks like the following.

Syntax

string.repeat(x)

IMPORTANT!

The (x) represents the number of times you want to repeat the string. If you don’t specify the value it will use 0 “Zero” as default value.

And if you try to use a negative value like in the example down below. It will throw a RangeError: repeat count must be non-negative.

const str = "I am a string";

console.log(str.repeat(-3));

string.repeat() method - Negative Input Range Error

And the same with Infinity, I don’t think we need an example so I will just show you the error.

RangeError: repeat count must be less than infinity and not overflow maximum string size.

Return

It will return a new string containing the number of copies specified in the method.

A value of 0 will return an empty string.

IMPORTANT!

This method does not change the original string, that’s why I said that it returns a new string.

Here some more examples, but also try it yourself and have fun.

string.repeat() method examples