The repeat() method of the String class in JavaScript returns a string consisting of the elements of the object repeated count times.
The syntax of String.repeat() method is:
repeat(count)
This repeat() method of String returns a string consisting of the elements of the object repeated count times.
Parameter | Optional/Required | Description |
---|---|---|
count | required | An integer indicating the number of times to repeat the string. |
String.repeat() returns value of type String
.
In JavaScript, the repeat()
method can be used to repeat a string a specified number of times.
For example,
str
with the value 'abc'
.repeat()
method with the count 3
to repeat the string three times.repeatedStr
.repeatedStr
to the console using the console.log()
method.const str = 'abc';
const repeatedStr = str.repeat(3);
console.log(repeatedStr);
abcabcabc
In JavaScript, if the repeat()
method is called with a count of 0, it returns an empty string.
For example,
str
with the value 'hello'
.repeat()
method with the count 0
to repeat the string zero times.repeatedStr
.repeatedStr
to the console using the console.log()
method.const str = 'hello';
const repeatedStr = str.repeat(0);
console.log(repeatedStr);
In JavaScript, if the repeat()
method is called with a count of 1, it returns the original string.
For example,
str
with the value 'world'
.repeat()
method with the count 1
to repeat the string once.repeatedStr
.repeatedStr
to the console using the console.log()
method.const str = 'world';
const repeatedStr = str.repeat(1);
console.log(repeatedStr);
world
In this JavaScript tutorial, we learned about repeat() method of String: the syntax and few working examples with output and detailed explanation for each example.