In vanilla JavaScript, the string repeat()
method lets you—well—repeat a string. I encountered it the other day after completing a challenge on Codewars and seeing others' solutions. I honestly had no idea it existed.
The challenge
"Write a function called repeatStr
which repeats the given string str
exactly num
times."
I swapped the str
and num
parameters around because I think they make more sense this way: pass in the string, then how many times you want to repeat it.
repeatStr('I', 6); // 'IIIIII'
repeatStr('Hello', 5); // 'HelloHelloHelloHelloHello'
My first solution
Unaware of the repeat()
method, my solution was to:
- Create an array with
num
empty slots - Fill each slot with the given string
str
- Join the values together into a single string
function repeatStr(str, num) {
return new Array(num).fill(str).join('');
}
Using the repeat() method
My solution worked, but after completeting the challenge and unlocking others' solutions, I learned that I could have just done this:
function repeatStr(str, num) {
return str.repeat(num);
}
Aside from teaching you about the repeat()
method, the purpose of this article is to remind you that you don't have to know everything to be a developer. It's all about being a lifelong learner and knowing what steps to take to solve a problem!
Learn more: The string repeat()
method in the MDN Web Docs.