Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

javascript

What is the String repeat() method in Javascript?

Talha Ashar

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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.

RELATED TAGS

javascript

CONTRIBUTOR

Talha Ashar
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring