Basic Algorithm Scripting: Repeat a String Repeat a String

Tell us what’s happening:
Instructions:
Repeat a given string str (first argument) for num times (second argument). Return an empty string if num is not a positive number.

So I have found a few different ways to repeat this string on different lines using a for loop. After doing that, I discovered they in fact want it all on the same line.

You can see below where I commented out using repeat (it was not in the instructions that you couldn’t use repeat so that was annoying because it works).

I had created returnState to either push() each iteration of the string into or concat() the strings together but couldn’t seem to get either to work.

when I get the desired result I will of course change the last console.log(blahblah) to return blahblah

I have also tried concat() with some multiplication like
str.concat(str*num) //(I don’t think this is the way to go)

Can someone help me get my strings on the same line?

Your code so far


function repeatStringNumTimes(str, num) {
  
if (num < 0) {
  return "";
} else{
  //console.log(str.repeat(num));
  //return str.repeat(num);
    let returnState = "";
    for (let i = 0; i < num; i++){
       console.log(str);
    }
  }  
}

repeatStringNumTimes("hello", 3);

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36.

Challenge: Repeat a String Repeat a String

Link to the challenge:

you need to return a value, not print it to the console
you have defined returnState but do nothing with it

yes, I forgot about that. Seems I should have clarified that part as well.

I had created returnState to either push() each iteration of the string into or concat() the strings together but couldn’t seem to get either to work.

when I get the desired result I will of course change the last console.log(blahblah) to return blahblah

follow up:

I figured it out.

function repeatStringNumTimes(str, num) {

if (num < 0) {

return "";

} else{

        let returnArry = [];

        for (let i = 0; i < num; i++){

          returnArry.push(str)

    }

      return returnArry.toString().replace(/,/g, '')     

    }  

}

repeatStringNumTimes(“abc”, 4);

I pushed each iteration into an array. Converted the array to a string. Then, removed the commas with replace.

Thanks for the help.

Thanks! This is much simpler.

function repeatStringNumTimes(str, num) {

let returnStr = ‘’;

for (let i = 0; i < num; i++){

  returnStr = str.concat(returnStr);

}

return returnStr

}

repeatStringNumTimes(“abc”, 3);

I would have used +=, but that works too! cong ratulations!

Ahhh yes. Thanks for the reminder.