JavaScript String repeat() – Repeat a String with Examples
This Snippet is coded by a user inOnline javascript Compiler. You can see and run this code too.
زبان: JavaScript
String.prototype.repeat() creates a new string by concatenating the original string a specified number of times. It takes one argument, count, and returns the repeated string without modifying the original value. For example, 'ab'.repeat(3) returns 'ababab', while 'x'.repeat(0) returns an empty string. The original string remains unchanged because JavaScript strings are immutable.
The method is called on a string and accepts a numeric count. The count is converted to an integer; negative values or Infinity throw a RangeError. Non-integer values are truncated during conversion. The output is always a new string, and the method is available in modern JavaScript environments (ES6+).
const result = 'ha'.repeat(3); // 'hahaha'
Time complexity is O(n × m), where n is the repeat count and m is the original string length, because the engine allocates and fills a new string of that size. Space complexity is O(n × m) for the resulting string. For very large counts, be mindful of memory limits, as the resulting string can grow quickly. Use repeat() for padding, separators, or generating repeated patterns. It is a concise alternative to loops and Array.join() for simple repetition tasks. If you need a separator between repetitions, combine it with Array(n).fill(str).join(sep) or similar. Always validate dynamic counts to avoid unexpected RangeError exceptions.