In this article we will learn how to repeat a string in JavaScript.
It is very common to repeat a string in JavaScript in JavaScript.
Problem
Now we have a problem which is that we want to repeat a string.
Imagine we have a string like this:
"Hello"
And we want to repeat this string 3x times.
Expected output like this:
"HelloHelloHello"
How to solve this problem?
This problem is easy to solve, and fortunately there is a built-in function that does it for us called repeat()
.
Repeat a string using repeat()
method
As we said before, we can use repeat
method to repeat a string more than one time.
Let's see an example
// String
const string = "Hello";
// Repeat
const result = string.repeat(3);
// Result:
console.log(result);
Output
HelloHelloHello
The repeat()
method constructs and returns a new string which contains the specified number of copies of the string on which it was called, concatenated together. MDN
Repeat a string using for
loop
We can use for
loop to repeat a string as well.
// String
let string = "Hello";
// Repeat
let repeatTimes = 3;
// Declare a variable
let result = "";
// For Loop
for (let i = 0; i < repeatTimes; i++) {
result += string;
}
// Result:
console.log(result);
Output
HelloHelloHello
Thank you for reading
Thank you for reading my blog. 🚀