JavaScript String.repeat() Method
-
Syntax of JavaScript
string.repeat()
: -
Use the Decimal Parameter Value for
string.repeat()
Method -
Use the Non-Integer Parameter Value for
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.