DEV Community

loading...

Repeat a String Repeat a String

Randy Rivera
Once I truly put my mind on something, I won't ever stop.
Updated on ・1 min read
  • 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

Discussion (0)