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 stringvar source = "Javascript with Educative! ";// create new repeat stringvar repeatString = source.repeat(5);// print stringsconsole.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 is invoked with the number of copies specified to be . Consequently, the repeat() method concatenates copies of source and returns the newly created string.
Free Resources