Repeating a String
String repeat: String.repeat()
The repeat()
method in JavaScript is used to create a new string by repeating the original string a specified number of times.
Syntax:
The parameters
- count: The number of times to repeat the original string. Must be a non-negative integer.
Return Value:
The repeat()
method returns a new string representing the original string repeated the specified number of times.
Example
In the example above, the repeat()
method is used to create a new string by repeating the original string โHello, โ three
times. The resulting string, โHello, Hello, Hello, โ, is stored in the variable repeatedString.
In this example, the repeat()
method is used to create a new string by repeating the original string โHello Javascript!โ zero
times. The resulting string is an empty string, "",
as the count is zero.
In this example, the repeat()
method is used with a non-integer count of 2.5
. The method automatically converts the count to an integer (2 in this case)
and repeats the original string 'repeatString()'
accordingly. The resulting string, โrepeatString()repeatString()โ, is stored in the variable repeatedString.
By using the String.repeat()
method, you can easily generate repeated strings, providing a convenient way to handle string repetition in JavaScript.