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);
|
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
let str = "gfg";
let repeatCount = str.repeat(5);
console.log(repeatCount);
|
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
let str = "gfg";
let repeatCount = str.repeat(2.9);
console.log(repeatCount);
|
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);
|
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
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!
Last Updated :
18 Jul, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...