How to Use the String repeat() Method in JavaScript

Contents
In this article, you will learn how to use the string repeat() method in JavaScript.
Using the string repeat() method in JavaScript
The repeat() method in JavaScript is used to create a new string by repeating a given string a specified number of times. This can be useful for generating placeholder text, creating patterns, or formatting strings.
Syntax
string.repeat(count)
Parameters
The repeat() method takes a single argument count, which specifies the number of times to repeat the string. The count argument must be a non-negative integer. If the count argument is negative or not a number, the repeat() method returns an empty string.
Examples
Basic usage
const str = "abc";
const repeatedStr = str.repeat(3);
console.log(repeatedStr); // "abcabcabc"
In this example, we defined a string str with the value “abc”. We used the repeat() method to create a new string repeatedStr by repeating the original string three times.
Generating a pattern
const star = "*";
const space = " ";
const pattern = star.repeat(5) + space.repeat(2) + star.repeat(3);
console.log(pattern); // "***** ***"
In this example, we defined two strings star and space with the values “*” and ” “, respectively. We used the repeat() method to generate a pattern by repeating the star character five times, then repeating the space character two times, and finally repeating the star character three times.
Using a variable for the repeat count
const str = "abc";
let count = 2;
const repeatedStr = str.repeat(count);
console.log(repeatedStr); // "abcabc"
In this example, we defined a string str with the value “abc” and a variable count with the value 2. We used the repeat() method to create a new string repeatedStr by repeating the original string a number of times specified by the count variable.
Handling edge cases
const str = "abc";
let count = -1;
const repeatedStr = str.repeat(count);
console.log(repeatedStr); // ""
In this example, we defined a string str with the value “abc” and a variable count with the value -1. Since the count argument is negative, the repeat() method returns an empty string.