In JavaScript, we can easily repeat a string as many times as we would like. The easiest way to repeat a string n times is to use the JavaScript String repeat() method.
var stringToRepeat = "string";
stringToRepeat = stringToRepeat.repeat(3);
console.log(stringToRepeat);
#Output:
stringstringstring
When using string variables in JavaScript, we can easily perform string manipulation to change the value of the string variables.
One such manipulation is repeating a string n times. We can repeat strings using the JavaScript String repeat() method.
The repeat() method takes one parameter, an integer, which is the number of times you want to repeat the string.
For example, if we want to repeat a string 3 times, we can simply just give the repeat() method the parameter 3, repeat(3);
Below is an example of how to repeat a string 3 times using JavaScript.
var stringToRepeat = "string";
stringToRepeat = stringToRepeat.repeat(3);
console.log(stringToRepeat);
#Output:
stringstringstring
If we want to repeat characters instead of strings, we can also do that using the repeat() method.
Repeat a String in JavaScript With a Loop
Another way we can repeat a string in JavaScript is by using a while loop.
var theString = "string";
var i = 0;
var repeatedString = "";
while (i < 3){
repeatedString = repeatedString + theString;
i++;
}
theString = repeatedString;
console.log(theString);
#Output:
stringstringstring
One of the benefits of repeating a string with a loop over the repeat() method is that we have more control.
So say that we wanted to add a space and comma in between each repeated string. We can do this easily with a loop.
var theString = "string";
var i = 0;
var repeatedString = "";
while (i < 3){
if( repeatedString != "" ){
repeatedString = repeatedString + ", " + theString;
} else {
repeatedString = theString;
}
i++;
}
theString = repeatedString;
console.log(theString);
#Output:
string, string, string
Hopefully this article has been useful for you to learn how to use JavaScript to repeat a string.