The program is very simple, we have to take a variable and return that variable being repeated certain amount of times. No need to add space or anything, just keep repeating it into one single string.
You can't edit strings, you will need to create a variable to store the new string.
Create a loop to repeat the code as many times as needed.
Make the variable created store the current value and append the word to it.
Solution ahead!
function repeat(str, num) {
var accumulatedStr = '';
while (num > 0) {
accumulatedStr += str;
num--;
}
return accumulatedStr;
}
Second Solution:
function repeat(str, num) {
var newstr = [];
for (var i = 0; i < num; i++) {
newstr.push(str);
}
return newstr.join('');
}
repeat("abc", 3);
- Create a variable to store the repeated word.
- Use a while loop or for loop to repeat code as many times as needed according to
num
- The we just have to add the string to the variable created on step one. and increase or decrease num depending on how you set the loop.
- At the end of the loop, return the variable for the repeated word.
Third Solution:
function repeat(str, num) {
if (num < 0) {
return "";
}
else {
return str.repeat(num);
}
}
repeat("abc", 3);
- First check if num is a negative number and return false if so
- as of ECMA Script 6 (ES6) the String object comes with a builtin function to repeat a string which we you can use
##Recursive Solution
function repeat(str, num) {
if(num < 0)
return "";
if(num === 1)
return str;
else
return str + repeat(str, num - 1);
}
If you found this page useful, you can give thanks by copying and pasting this on the main chat: Thanks @Rafase282 @shadowfool for your help with Bonfire: Repeat a String Repeat a String
NOTE: Please add your username only if you have added any relevant main contents to the wiki page. (Please don't remove any existing usernames.)