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:
count
: An integer that specifies the number of times to repeat the string. If this parameter is less than zero, it throws aRangeError
. If it isInfinity
, it is treated as0
, 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
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.
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.
Example 4: Non-integer Count
If a non-integer count is provided, it is truncated to the nearest integer.
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.
Output:
Example 6: Dynamic Content Generation
You can also use repeat()
for dynamically generating content based on user input or application logic.
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.