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

ParameterOptional/RequiredDescription
countrequiredAn 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,

  1. We define a string variable str with the value 'abc'.
  2. We use the repeat() method with the count 3 to repeat the string three times.
  3. The result is stored in the variable repeatedStr.
  4. We log repeatedStr to the console using the console.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,

  1. We define a string variable str with the value 'hello'.
  2. We use the repeat() method with the count 0 to repeat the string zero times.
  3. The result is stored in the variable repeatedStr.
  4. We log repeatedStr to the console using the console.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,

  1. We define a string variable str with the value 'world'.
  2. We use the repeat() method with the count 1 to repeat the string once.
  3. The result is stored in the variable repeatedStr.
  4. We log repeatedStr to the console using the console.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.