[javascript] Repeat a string in JavaScript a number of times

In Perl I can repeat a character multiple times using the syntax:

$a = "a" x 10; // results in "aaaaaaaaaa"

Is there a simple way to accomplish this in Javascript? I can obviously use a function, but I was wondering if there was any built in approach, or some other clever technique.

This question is related to javascript string character repeat

The answer is


this is how you can call a function and get the result by the helps of Array() and join()

_x000D_
_x000D_
function repeatStringNumTimes(str, num) {_x000D_
  // repeat after me_x000D_
  return num > 0 ? Array(num+1).join(str) : "";_x000D_
}_x000D_
_x000D_
console.log(repeatStringNumTimes("a",10))
_x000D_
_x000D_
_x000D_


Right pads with zeros with no arrays or loops. Just uses repeat() using ES6 2015, which has wide support now. Left pads if you switch the concatenation.

function pad(text, maxLength){ 
  var res = text + "0".repeat(maxLength - text.length);
  return res;
}

console.log(pad('hello', 8)); //hello000

Here is an ES6 version

_x000D_
_x000D_
const repeat = (a,n) => Array(n).join(a+"|$|").split("|$|");_x000D_
repeat("A",20).forEach((a,b) => console.log(a,b+1))
_x000D_
_x000D_
_x000D_


In ES2015/ES6 you can use "*".repeat(n)

So just add this to your projects, and your are good to go.

  String.prototype.repeat = String.prototype.repeat || 
    function(n) {
      if (n < 0) throw new RangeError("invalid count value");
      if (n == 0) return "";
      return new Array(n + 1).join(this.toString()) 
    };

An alternative is:

for(var word = ''; word.length < 10; word += 'a'){}

If you need to repeat multiple chars, multiply your conditional:

for(var word = ''; word.length < 10 * 3; word += 'foo'){}

NOTE: You do not have to overshoot by 1 as with word = Array(11).join('a')


String.prototype.repeat = function (n) { n = Math.abs(n) || 1; return Array(n + 1).join(this || ''); };

// console.log("0".repeat(3) , "0".repeat(-3))
// return: "000" "000"

I'm going to expand on @bonbon's answer. His method is an easy way to "append N chars to an existing string", just in case anyone needs to do that. For example since "a google" is a 1 followed by 100 zeros.

_x000D_
_x000D_
for(var google = '1'; google.length < 1 + 100; google += '0'){}_x000D_
document.getElementById('el').innerText = google;
_x000D_
<div>This is "a google":</div>_x000D_
<div id="el"></div>
_x000D_
_x000D_
_x000D_

NOTE: You do have to add the length of the original string to the conditional.


In a new ES6 harmony, you will have native way for doing this with repeat. Also ES6 right now only experimental, this feature is already available in Edge, FF, Chrome and Safari

"abc".repeat(3) // "abcabcabc"

And surely if repeat function is not available you can use old-good Array(n + 1).join("abc")


If you're not opposed to including a library in your project, lodash has a repeat function.

_.repeat('*', 3);
// ? '***

https://lodash.com/docs#repeat


/**  
 * Repeat a string `n`-times (recursive)
 * @param {String} s - The string you want to repeat.
 * @param {Number} n - The times to repeat the string.
 * @param {String} d - A delimiter between each string.
 */

var repeat = function (s, n, d) {
    return --n ? s + (d || "") + repeat(s, n, d) : "" + s;
};

var foo = "foo";
console.log(
    "%s\n%s\n%s\n%s",

    repeat(foo),        // "foo"
    repeat(foo, 2),     // "foofoo"
    repeat(foo, "2"),   // "foofoo"
    repeat(foo, 2, "-") // "foo-foo"
);

Lodash offers a similar functionality as the Javascript repeat() function which is not available in all browers. It is called _.repeat and available since version 3.0.0:

_.repeat('a', 10);

For all browsers

The following function will perform a lot faster than the option suggested in the accepted answer:

var repeat = function(str, count) {
    var array = [];
    for(var i = 0; i < count;)
        array[i++] = str;
    return array.join('');
}

You'd use it like this :

var repeatedString = repeat("a", 10);

To compare the performance of this function with that of the option proposed in the accepted answer, see this Fiddle and this Fiddle for benchmarks.

For moderns browsers only

In modern browsers, you can now do this using String.prototype.repeat method:

var repeatedString = "a".repeat(10);

Read more about this method on MDN.

This option is even faster. Unfortunately, it doesn't work in any version of Internet explorer. The numbers in the table specify the first browser version that fully supports the method:

enter image description here


For repeat a value in my projects i use repeat

For example:

var n = 6;
for (i = 0; i < n; i++) {
    console.log("#".repeat(i+1))
}

but be careful because this method has been added to the ECMAScript 6 specification.


function repeatString(n, string) {
  var repeat = [];
  repeat.length = n + 1;
  return repeat.join(string);
}

repeatString(3,'x'); // => xxx
repeatString(10,''); // => ""

var stringRepeat = function(string, val) {
  var newString = [];
    for(var i = 0; i < val; i++) {
      newString.push(string);
  }
  return newString.join('');
}

var repeatedString = stringRepeat("a", 1);

Here is what I use:

function repeat(str, num) {
        var holder = [];
        for(var i=0; i<num; i++) {
            holder.push(str);
        }
        return holder.join('');
    }

Convenient if you repeat yourself a lot:

_x000D_
_x000D_
String.prototype.repeat = String.prototype.repeat || function(n){_x000D_
  n= n || 1;_x000D_
  return Array(n+1).join(this);_x000D_
}_x000D_
_x000D_
alert(  'Are we there yet?\nNo.\n'.repeat(10)  )
_x000D_
_x000D_
_x000D_


Another interesting way to quickly repeat n character is to use idea from quick exponentiation algorithm:

var repeatString = function(string, n) {
    var result = '', i;

    for (i = 1; i <= n; i *= 2) {
        if ((n & i) === i) {
            result += string;
        }
        string = string + string;
    }

    return result;
};

The most performance-wice way is https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/repeat

Short version is below.

  String.prototype.repeat = function(count) {
    if (count < 1) return '';
    var result = '', pattern = this.valueOf();
    while (count > 1) {
      if (count & 1) result += pattern;
      count >>>= 1, pattern += pattern;
    }
    return result + pattern;
  };
  var a = "a";
  console.debug(a.repeat(10));

Polyfill from Mozilla:

if (!String.prototype.repeat) {
  String.prototype.repeat = function(count) {
    'use strict';
    if (this == null) {
      throw new TypeError('can\'t convert ' + this + ' to object');
    }
    var str = '' + this;
    count = +count;
    if (count != count) {
      count = 0;
    }
    if (count < 0) {
      throw new RangeError('repeat count must be non-negative');
    }
    if (count == Infinity) {
      throw new RangeError('repeat count must be less than infinity');
    }
    count = Math.floor(count);
    if (str.length == 0 || count == 0) {
      return '';
    }
    // Ensuring count is a 31-bit integer allows us to heavily optimize the
    // main part. But anyway, most current (August 2014) browsers can't handle
    // strings 1 << 28 chars or longer, so:
    if (str.length * count >= 1 << 28) {
      throw new RangeError('repeat count must not overflow maximum string size');
    }
    var rpt = '';
    for (;;) {
      if ((count & 1) == 1) {
        rpt += str;
      }
      count >>>= 1;
      if (count == 0) {
        break;
      }
      str += str;
    }
    // Could we try:
    // return Array(count + 1).join(this);
    return rpt;
  }
}

Array(10).fill('a').join('')

Although the most voted answer is a bit more compact, with this approach you don't have to add an extra array item.


Can be used as a one-liner too:

function repeat(str, len) {
    while (str.length < len) str += str.substr(0, len-str.length);
    return str;
}

In CoffeeScript:

( 'a' for dot in [0..10]).join('')

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to character

Set the maximum character length of a UITextField in Swift Max length UITextField Remove last character from string. Swift language Get nth character of a string in Swift programming language How many characters can you store with 1 byte? How to convert integers to characters in C? Converting characters to integers in Java How to check the first character in a string in Bash or UNIX shell? Invisible characters - ASCII How to delete Certain Characters in a excel 2010 cell

Examples related to repeat

Create an array with same element repeated multiple times Fastest way to count number of occurrences in a Python list Repeat rows of a data.frame make image( not background img) in div repeat? Create sequence of repeated values, in sequence? Finding repeated words on a string and counting the repetitions do-while loop in R Repeat string to certain length Repeat a string in JavaScript a number of times