Repeating a string n number of times in JavaScript
Learn, how to repeat a string in JavaScript.
To repeat a string in a specified number of times, we can use the built-in repeat() method in JavaScript.
Here is an example that repeats the following string for 4 times:
const name = "king";
const repeat = name.repeat(4);
console.log(repeat);Output:
"kingkingkingking"Similarly, we can also create our repeat() function like this:
function repeat(str, n) {
if (!str || !n) {
return;
}
let final = "";
while (n) {
final += s;
n--;
}
return final;
}
console.log(repeat("sai", 3)); // "saisaisai"In the above function, we have used the while loop to concatenate the string for n number of times.


