JavaScript repeat string


Built-in

To repeat a string a number times in JavaScript, use the built-in String.prototype.repeat().

Here’s an example that repeats Na 16 times:

'Na'.repeat(16) + ' Batman!'; // 'NaNaNaNaNaNaNaNaNaNaNaNaNaNaNaNa Batman!'

This method is supported across all browers except IE. If you can’t wait until Internet Explorer is deprecated (August 17, 2021), you can write your own function or polyfill.

Function

To repeat a string N times using a custom function:

/**
 * Repeat a string N times.
 *
 * @param  {string} string
 * @param  {number} [count]
 * @return {string}
 */
function repeat(string, count) {
  if (!string || !count) {
    return '';
  }
  return Array(count + 1).join(string);
}

Combination

To combine the built-in method and the custom function into one:

/**
 * Repeat a string N times.
 *
 * @param  {string} string
 * @param  {number} [count]
 * @return {string}
 */
function repeat(string, count) {
  if (!string || !count) {
    return '';
  }
  if (typeof string.repeat === 'function') {
    return string.repeat(count);
  }
  return Array(count + 1).join(string);
}


Please support this site and join our Discord!