What is the String repeat() method in Javascript?

The repeat() method of the String class in Javascript creates a new string that contains a specified number of copies of a provided string. The copies of the provided string are concatenated to construct the new string.

The process is illustrated below:

The prototype of the repeat() method is shown below:

string.repeat(count)

In the command shown above, string represents any string object.

Parameters

The repeat() method takes a single mandatory parameter, i.e., an integer that specifies the number of times the string needs to be repeated.

Return value

The repeat() method returns a new string that contains the specified number of copies of the provided string.

Example

The code below shows how the repeat() method works in Javascript:

// initialize source string
var source = "Javascript with Educative! ";
// create new repeat string
var repeatString = source.repeat(5);
// print strings
console.log("The original string was:\'", source, "\'.");
console.log("The new repeat string is: \'", repeatString, "\'.");

Explanation

First, a string variable, source, is initialized. The final character to the string source is a space character to allow for separation between the copies of the string when the repeat() method is invoked.

The repeat() method in line 55 is invoked with the number of copies specified to be 55. Consequently, the repeat() method concatenates 55 copies of source and returns the newly created string.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved