JavaScript String.repeat() Method

Shubham Vora Jan 30, 2023
  1. Syntax of JavaScript string.repeat():
  2. Use the Decimal Parameter Value for string.repeat() Method
  3. Use the Non-Integer Parameter Value for string.repeat() Method
JavaScript String.repeat() Method

The String repeat() method is a built-in JavaScript method that creates the new string by appending the particular number of copies of the reference string.

Syntax of JavaScript string.repeat():

referenceString.repeat(count);

Parameters

count To generate the new string with total count copies

Return

It returns the new string without altering the reference string.

Use the Decimal Parameter Value for string.repeat() Method

The JavaScript string.repeat() method takes the positive value as a parameter to repeat the string a particular number of times. In the example below, we pass the decimal values as a parameter of the repeat() method, which will return a new string with a particular number of copies.

let referenceString = "DelfStack! ";
let count = 3;
let repeatingString = referenceString.repeat(count);
console.log(repeatingString);

Output:

DelfStack! DelfStack! DelfStack!

Use the Non-Integer Parameter Value for string.repeat() Method

When we use the non-integer value as the parameter of the string.repeat() method, it rounds down the count value to convert it to an integer value and returns the new string with an integer count number of copies. In the example below, we have passed the non-integer value as a parameter of the string.repeat() method.

let baseString = "DelfStack! ";
let count = 2.9;
let outputString = baseString.repeat(count);
console.log(outputString);

Output:

DelfStack! DelfStack!

The string.repeat() method is compatible with the most modern browser. Users can use it to generate a new string by concatenaing the same string several times.

Author: Shubham Vora
Shubham Vora avatar Shubham Vora avatar

Shubham is a software developer interested in learning and writing about various technologies. He loves to help people by sharing vast knowledge about modern technologies via different platforms such as the DelftStack.com website.

LinkedIn GitHub

Related Article - JavaScript String