In JavaScript, we can repeat a character n times by making use of the JavaScript String repeat() method.
var characterToRepeat = "s";
characterToRepeat = characterToRepeat.repeat(10);
console.log(characterToRepeat);
#Output:
ssssssssss
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 character in strings many times. We can repeat characters in a string 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);
Repeating strings is very similar to repeating characters. Check out how to do that here.
Repeat all characters in a string n times in JavaScript
In the above example, we showed how to repeat one character. Let’s say we have a string called, “string” and we want to repeat all characters n times.
We would just need the help of a for loop along with the repeat() method and the length() and charAt() methods to make this happen.
Here is our code to repeat characters in a string n times:
var theString = "string";
var newString = "";
for (var i=0; i < theString.length; i++){
var currChar = theString.charAt(i);
currChar = currChar.repeat(n);
newString = newString + currChar;
}
So say we wanted to repeat all characters of a string 5 times, we could use our code above to do this.
var theString = "string";
var newString = "";
for (var i=0; i < theString.length; i++){
var currChar = theString.charAt(i);
currChar = currChar.repeat(5);
newString = newString + currChar;
}
console.log(newString);
#Output:
ssssstttttrrrrriiiiinnnnnggggg
Hopefully this article has been helpful for you to learn how to use JavaScript to repeat a character n times.