Monday, November 18, 2024
Google search engine
HomeLanguagesJavascriptJavaScript String repeat() Method

JavaScript String repeat() Method

The string.repeat() is an inbuilt method in JavaScript that is used to build a new string containing a specified number of copies of the string on which this method has been called.

Syntax:

string.repeat(count);

Parameters: This method accepts a single parameter.

  • count: count is an integer value that shows the number of times to repeat the given string. The range of the integer “count” is from zero (0) to infinity.

Return values: It returns a new string that contains the specified number of copies of the string.

Below is an example of the string.repeat() Method. 

Example 1: In this example, we will repeat the string value two times using the string.repeat() method and print it in the console.

Javascript




let str = "forGeeks";
let repeatCount = str.repeat(2);
console.log(repeatCount);


Output

forneveropen

Example 2:  In this example, we will repeat the string value five times using the string.repeat() method and print it in the console.

Javascript




// Taking a string "gfg"
let str = "gfg";
 
// Repeating the string multiple times
let repeatCount = str.repeat(5);
console.log(repeatCount);


Output

gfggfggfggfggfg

Example 3: In this example, we will repeat the string value 2.9 times using the string.repeat() method, we will see that it only prints two times as 2.9 is converted to 2.

Javascript




// Taking a string "gfg"
let str = "gfg";
 
// Repeating the string 2.9 times i.e, 2 times
// because 2.9 converted into 2
let repeatCount = str.repeat(2.9);
console.log(repeatCount);


Output

gfggfg

Example: In this example,we are using a for loop, we iterate repeatCount times and concatenate the original string

Javascript




let str = "Geeks";
let repeatCount = 3;
let repeatedStr = "";
 
for (let i = 0; i < repeatCount; i++) {
    repeatedStr += str;
}
 
console.log(repeatedStr);


Output

GeeksGeeksGeeks

We have a complete list of Javascript string methods, to check those please go through this Javascript String Complete reference article.

Supported Browsers:

  • Google Chrome 41 and above
  • Edge 12 and above
  • Firefox 24 and above
  • Opera 28 and above
  • Safari 9 and above

RELATED ARTICLES

Most Popular

Recent Comments