Repeat a String - JavaScript Solution & Walkthrough
(07/16) Learn how to solve coding challenges using FreeCodeCamp's curriculum.
07/16 Repeat a String Repeat a String
Repeat a given string
str
(first argument) fornum
times (second argument). Return an empty string ifnum
is not a positive number. For the purpose of this challenge, do not use the built-in.repeat()
method.
function repeatStringNumTimes(str, num) {
return str;
}
repeatStringNumTimes("abc", 3);
Credit: FreeCodeCamp.org
Understanding the Challenge
In this challenge, you'll be given a string str
as first argument of the function. And a number num
as second argument.
Your task here is to complete the function such that it returns str
repeated multiple times. In the given example, str
is given as "abc" and num
is given as 3
. In this case, the function is expected to return abcabcabc
.
You've also been given two things to take note of. First, if num
is not a positive number, return an empty. And secondly, "do not use the built-in .repeat()
method."
Pseudocode
Given a string(str) and a number(num)
Check if num is a positive number
if num is not a positive number
return an empty string
if num is a positive number
return str repeated num times
Solving the Challenge
First, we shall declare a variable and set it to an empty string. let's call it finalString
let finalString = ""
Next, we'll check whether num
is positive or not. If num is not positive, that is num <= 0, we'll return finalString which is an empty string.
if (num <= 0) {
return finalString
}
We can now add an else
statement to handle a situation where num
is positive.
For a positive num
, we'll need a loop. We'll initiate the loop at i = 1
and keep the loop running as long as i <= num
.
For each iteration, concatenate the given string str
to the current value of finalString
if (num <= 0) {
return finalString
} else {
for (let i = 1; i <= num; i++) {
finalString += str;
}
We return finalString
after the loop is done.
return finalString;
Our repeatStringNumTimes
is now complete!
Final Solution
function repeatStringNumTimes(str, num) {
let finalString = "";
if (num <= 0) {
return finalString;
} else {
for (let i = 1; i <= num; i++) {
finalString += str
}
return finalString;
}
}
repeatStringNumTimes("abc", 3); // abcabcabc
Congratulations!
You just cracked the seventh challenge in this series.
Cheers and happy coding!