DEV Community

Randy Rivera
Randy Rivera

Posted on • Edited on

Repeat a String Repeat a String

  • Repeat a given string str(first argument) for num times (second argument). Return an empty string if num is not a positive number. You can also use the built-in .repeat() method or recursion.
function repeatStringNumTimes(str, num) {
  return str;
}

repeatStringNumTimes("abc", 3);
Enter fullscreen mode Exit fullscreen mode
  • This could be done with .repeat() method like so:
 if (num < 0) return ""; 
 return str.repeat(num); // would console log abcabcabc;
Enter fullscreen mode Exit fullscreen mode
  • Also recursion would work here like so;
function repeatStringNumTimes(str, num) {
 if (num <= 0) return "";
 if (num === 1) return str; //base case
 return str + repeatStringNumTimes(str, num - 1);
};
repeatingStringNumTimes("abc", 3);
// "abc" + repeatStringNumTimes("abc", 2)
// "abc" + repeatStringNumTimes("abc", 1)
// "abc"
Enter fullscreen mode Exit fullscreen mode
function repeatStringNumTimes(str, num) {
  let final = "";
  if (num < 0) return "";
  for (let i = 0; i < num; i++) {
    final = final + str;
  }
  return final;
}

console.log(repeatStringNumTimes("abc", 3)); // will display abcabcabc
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
myblood profile image
Alexandr Vasilyev

@rthefounding Thank you!
I think you already know, but here are some pretty great solutions, for analysis and your own learning)
forum.freecodecamp.org/t/freecodec...