JavaScript string repeat method:
To repeat a string for a specific number of times, JavaScript provides one method called repeat.
In this post, I will show you how to use repeat with an example.
Syntax of string.repeat:
repeat method is defined as below:
string.repeat([count])
Here, count is an optional value. It is the number to repeat the string. If we don’t provide this value, it will return an empty string. Else, it will create a new string by appending the same string to the end and return that string.
Return value:
This method doesn’t change the original string. It creates one new string by repeating the original string count number of times.
For count equal to 0 or if we don’t provide the count value, it will return an empty string.
For a negative count value, it throws one RangeError.
Example program:
Let’s take a look at the below program:
const givenStr = 'hello';
console.log(givenStr.repeat())
console.log(givenStr.repeat(0))
console.log(givenStr.repeat(1))
console.log(givenStr.repeat(2))
console.log(givenStr.repeat(3))
It will print the below output:
hello
hellohello
hellohellohello
For the first two, it printed empty strings.
You might also like:
- 2 different JavaScript program to calculate age from date of birth
- How to print a multiplication table in HTML,CSS, and JavaScript
- JavaScript program to get the selected value from a dropdown list of items
- How to stop forEach() method in JavaScript
- 3 different JavaScript program to convert a set to array
- JavaScript program to convert Celsius to Fahrenheit