JavaScript repeat() method


The repeat() method in JavaScript is used to create a new string by repeating the original string a specified number of times. This method is useful for generating repeated sequences of characters or creating formatted text.

Syntax:

string.repeat(count)
  • count: An integer that specifies the number of times to repeat the string. If this parameter is less than zero, it throws a RangeError. If it is Infinity, it is treated as 0, and if it is a non-integer, it is truncated to the nearest integer.

Return Value:

  • Returns a new string that consists of the original string repeated count times.

Example 1: Basic Usage

let str = "Hello "; let repeatedStr = str.repeat(3); console.log(repeatedStr); // "Hello Hello Hello "

In this example, the string "Hello " is repeated 3 times.

Example 2: Zero Count

If the count is zero, the method returns an empty string.

let str = "Test"; let repeatedStr = str.repeat(0); console.log(repeatedStr); // ""

Here, repeating the string "Test" zero times results in an empty string.

Example 3: Negative Count

If a negative count is provided, a RangeError is thrown.

try { let str = "Error"; let repeatedStr = str.repeat(-1); } catch (error) { console.log(error); // RangeError: count must be a positive integer }

Example 4: Non-integer Count

If a non-integer count is provided, it is truncated to the nearest integer.

let str = "Repeat "; let repeatedStr = str.repeat(2.5); console.log(repeatedStr); // "Repeat Repeat "

In this case, the count is truncated to 2, resulting in the string being repeated twice.

Example 5: Formatting Output

You can use repeat() for formatting purposes, such as creating a decorative border or repeating characters for visual separation.

let border = "*".repeat(10); console.log(border); // "**********" let message = "Hello World!"; console.log(border); console.log(message); console.log(border);

Output:

********** Hello World! **********

Example 6: Dynamic Content Generation

You can also use repeat() for dynamically generating content based on user input or application logic.

function createProgressBar(percentage) { let filled = "█".repeat(percentage / 10); let empty = "░".repeat(10 - (percentage / 10)); return `[${filled}${empty}] ${percentage}%`; } console.log(createProgressBar(75)); // "[█████████░░] 75%"

In this example, the progress bar is created dynamically based on the given percentage.

Summary:

  • The repeat() method is used to create a new string by repeating the original string a specified number of times.
  • It takes one parameter: count, which indicates how many times to repeat the string.
  • If the count is zero, an empty string is returned; if it's negative, a RangeError is thrown.
  • This method is useful for generating repeated sequences, formatting output, and dynamically creating content based on conditions.