JavaScript String repeat()
Syntax & Examples
String.repeat() method
The repeat() method of the String class in JavaScript returns a string consisting of the elements of the object repeated count times.
Syntax of String.repeat()
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.
Parameters
| Parameter | Optional/Required | Description |
|---|---|---|
count | required | An integer indicating the number of times to repeat the string. |
Return Type
String.repeat() returns value of type String.
✐ Examples
1 Using repeat() method to repeat a string multiple times
In JavaScript, the repeat() method can be used to repeat a string a specified number of times.
For example,
- We define a string variable
strwith the value'abc'. - We use the
repeat()method with the count3to repeat the string three times. - The result is stored in the variable
repeatedStr. - We log
repeatedStrto the console using theconsole.log()method.
JavaScript Program
const str = 'abc';
const repeatedStr = str.repeat(3);
console.log(repeatedStr);Output
abcabcabc
2 Using repeat() method with a count of 0
In JavaScript, if the repeat() method is called with a count of 0, it returns an empty string.
For example,
- We define a string variable
strwith the value'hello'. - We use the
repeat()method with the count0to repeat the string zero times. - The result is stored in the variable
repeatedStr. - We log
repeatedStrto the console using theconsole.log()method.
JavaScript Program
const str = 'hello';
const repeatedStr = str.repeat(0);
console.log(repeatedStr);Output
3 Using repeat() method with a count of 1
In JavaScript, if the repeat() method is called with a count of 1, it returns the original string.
For example,
- We define a string variable
strwith the value'world'. - We use the
repeat()method with the count1to repeat the string once. - The result is stored in the variable
repeatedStr. - We log
repeatedStrto the console using theconsole.log()method.
JavaScript Program
const str = 'world';
const repeatedStr = str.repeat(1);
console.log(repeatedStr);Output
world
Summary
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.