Repeat String with repeat()
Write a JavaScript function that takes a string and a count, and returns a new string consisting of the original string repeated count times using String.repeat().
String.prototype.repeat() was introduced in ES6 and constructs and returns a new string containing the specified number of copies of the calling string, concatenated together. If the count is 0, an empty string is returned. If the count is negative or Infinity, a RangeError is thrown.
The repeat() method is the simplest way to repeat strings in JavaScript. Before ES6, developers used manual loops or Array.join() tricks. The repeat() method is more readable and more efficient than these workarounds. It is widely supported in all modern JavaScript environments.
Time complexity is O(n * m) where n is the count and m is the string length. Space complexity is O(n * m) for the result string. The method creates a new string without modifying the original.
Edge cases include count 0 (returns empty string), count 1 (returns the string itself), and ensuring the count is a non-negative integer. Negative or fractional counts throw errors.
Example Input & Output
Repeat once
Repeat twice
Repeat ha 3 times
Repeat 0 returns empty
Repeat x 5 times
Algorithm Flow

Solution Approach
Best Answers
function solution(str, count) {
return str.repeat(count);
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
