Sometimes, we’ve to create a string that’s generated by repeating a string a number of times in our JavaScript code.
In this article, we’ll look at how to repeat string in JavaScript easily.
String.prototype.repeat
The repeat
method that comes with JavaScript strings lets us create a string that’s created by repeating the string that it’s called on.
For instance, we can write:
const str = "b".repeat(10)
console.log(str);
We call repeat
with number of times we want to repeat 'b'
for.
So str
is ‘bbbbbbbbbb’
.
Array Constructor
We can use the Array
constructor to create an array with the given number of empty slots.
And we can call join
on it with the striogn we want to repeat it.
For instance, we can write:
const str = Array(11).join("b")
console.log(str);
The length of the array is 1 bigger than the number of times we want to repeat the string.
This is because join
puts the string in between the array entries.
So we get the same result as before.
Use a Loop
We can use a loop to create the repeated string.
For instance, we can write:
let word = ''
for (let times = 0; times < 10; times++) {
word += 'b'
}
console.log(word)
We create a for loop that runs for 10 iterations.
And in the loop body, we append the string we want into the word
string.
And so word
is 'bbbbbbbbbb’
like we have before.
Lodash repeat Method
Since Lodash 3.0.0, it comes with the repeat
method that lets us return a string that’s the repeat of a given substring by the given number of times.
For instance, we can write:
const word = _.repeat('b', 10)
console.log(word)
Then word
is 'bbbbbbbbbb’
since we specified that we want to repeat 'b'
for 10 times.
Conclusion
We can repeat a string with the Lodash repeat
method or the native string repeat
method.
Also, we can use a loop to append a string.