Code Logo

Repeat String with repeat()

Published at25 Jul 2026
JavaScript String Handling Easy 0 views
Like0

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

Example 1
Input
"abc",1
Output
"abc"
Explanation

Repeat once

Example 2
Input
"ok",2
Output
"okok"
Explanation

Repeat twice

Example 3
Input
"ha",3
Output
"hahaha"
Explanation

Repeat ha 3 times

Example 4
Input
"test",0
Output
""
Explanation

Repeat 0 returns empty

Example 5
Input
"x",5
Output
"xxxxx"
Explanation

Repeat x 5 times

Algorithm Flow

Recommendation Algorithm Flow for Repeat String with repeat()
Recommendation Algorithm Flow for Repeat String with repeat()

Solution Approach

function solution(str, count) {
  return str.repeat(count);
}

Best Answers

javascript - Approach 1
function solution(str, count) {
  return str.repeat(count);
}