842

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.

Timo Tijhof
  • 10,032
  • 6
  • 34
  • 48
Steve
  • 53,375
  • 33
  • 96
  • 141

24 Answers24

1617

These days, the repeat string method is implemented almost everywhere. (It is not in Internet Explorer.) So unless you need to support older browsers, you can simply write:

"a".repeat(10)

Before repeat, we used this hack:

Array(11).join("a") // create string with 10 a's: "aaaaaaaaaa"

(Note that an array of length 11 gets you only 10 "a"s, since Array.join puts the argument between the array elements.)

Simon also points out that according to this benchmark, it appears that it's faster in Safari and Chrome (but not Firefox) to repeat a character multiple times by simply appending using a for loop (although a bit less concise).

EscapeNetscape
  • 2,892
  • 1
  • 33
  • 32
Jason Orendorff
  • 42,793
  • 6
  • 62
  • 96
  • 6
    Plus, you can use a variable instead of a fixed length - Array(20-len), say to pad a string up to 20. – John C Jun 28 '12 at 16:42
  • 8
    The loop method may be faster but its more verbose. Plus I'm puzzled by all the upvotes for the first comment, considering that when this is generally going to be useful when the Array length is variable, e.g. `Array(rawValue.length + 1).join("*")` – Dexygen Jan 30 '15 at 19:30
  • It doesn't work when you try with the power of 10 12 times (Math.pow(10, 12)) Array(Math.pow(10, 12)).join("a") – Neel Rathod Aug 06 '19 at 05:57
  • 3
    @Neel That's because JS engines impose a limit on string length. In Chrome and Firefox, the limit is close to 2^30 (about a billion). 10^12 is one trillion. – Jason Orendorff Aug 13 '19 at 13:18
  • 1
    (I wonder what this string is that a thousand programmers are so keen to repeat. Haven't y'all heard of DRY?) – Jason Orendorff Feb 21 '21 at 16:49
321

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")

Salvador Dali
  • 214,103
  • 147
  • 703
  • 753
56

Convenient if you repeat yourself a lot:

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

alert(  'Are we there yet?\nNo.\n'.repeat(10)  )
vsync
  • 118,978
  • 58
  • 307
  • 400
kennebec
  • 102,654
  • 32
  • 106
  • 127
  • 56
    It's a bad coding practice to pollute builtins' prototypes. – tuomassalo Feb 09 '12 at 00:57
  • 3
    @nurettin see http://programmers.stackexchange.com/questions/104320/why-is-extending-the-dom-built-in-object-prototypes-a-bad-idea for more discussion. I'd add a (properly scoped) static helper function, with a signature of `repeat(str, n)`. – tuomassalo May 27 '13 at 08:25
  • 5
    I'd remove the `n= n || 1` part (or check if `n` is undefined), so you can also repeat `0` times. – chodorowicz Jul 09 '13 at 13:55
  • 4
    Also have a look at Mozilla's official polyfill for ES6: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/repeat – Eirik Birkeland Dec 11 '15 at 07:08
  • @tuomassalo a polyfill is not pollution (though as Eirik hints, a [complete polyfill](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/repeat#Polyfill) is a bit more complex) – ChrisV Oct 14 '16 at 10:28
  • 3
    @ChrisV, `String.repeat` was only added in ES6, which wasn't finalized until June 2015. So I think my point was valid when I wrote it in 2012. :) – tuomassalo Oct 14 '16 at 10:38
  • You know you can get the [Disciplined badge](https://stackoverflow.com/help/badges/37/disciplined) by deleting this answer? This is by now overriding ES6's `.repeat` function, besides being bad practice. – Adelin Mar 19 '18 at 10:28
  • 1
    @Adelin, these comments (including yours; never knew about that badge) are worth keeping the answer. At present this answer has 55 votes vs the top answer with 1,342, I doubt anyone would mistake this for the best solution. – elPastor May 27 '21 at 00:49
18
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.

Grzegorz Pawlik
  • 2,198
  • 1
  • 18
  • 18
15

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')

Bruno Bronosky
  • 66,273
  • 12
  • 162
  • 149
bonbon
  • 243
  • 4
  • 11
13

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;
  }
}
  • This is a good one, but the new native "repeat" is even faster and needs no implementation, thanks anyway! – Goty Metal Jan 02 '17 at 14:06
  • 1
    can you elaborate on the meaning of `count >>>= 1, pattern += pattern;`? what kind of statement is it? – Tsahi Asher Apr 03 '17 at 13:05
  • So this is a polyfill for the native repeat, then? Just add an `if (!String.prototype.repeat) {` to the beginning and `}` to the end. – trlkly Jun 20 '17 at 23:23
  • >>>= is unsigned right shift assignment (as in count = count >>> 1) see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Assignment_Operators#Unsigned_right_shift_assignment – user1441004 Jan 21 '18 at 21:18
11

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

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

https://lodash.com/docs#repeat

Nathan Danger
  • 155
  • 1
  • 7
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

John Slegers
  • 45,213
  • 22
  • 199
  • 169
8

String.repeat() is supported by 96.39% of browsers as of now.

function pad(text, maxLength){ 
  return text + "0".repeat(maxLength - text.length);
}
console.log(pad('text', 7)); //text000
Victor Stoddard
  • 3,582
  • 2
  • 27
  • 27
7

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()) 
    };
webdeb
  • 12,993
  • 5
  • 28
  • 44
6
/**  
 * 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"
);
yckart
  • 32,460
  • 9
  • 122
  • 129
5

Just for the fun of it, here is another way by using the toFixed(), used to format floating point numbers.

By doing

(0).toFixed(2)
(0).toFixed(3)
(0).toFixed(4)

we get

0.00
0.000
0.0000

If the first two characters 0. are deleted, we can use this repeating pattern to generate any repetition.

function repeat(str, nTimes) {
  return (0).toFixed(nTimes).substr(2).replaceAll('0', str);
}

console.info(repeat('3', 5));
console.info(repeat('hello ', 4));
Jose Rui Santos
  • 15,009
  • 9
  • 58
  • 71
  • [`toFixed`](//developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed) can only handle a precision of 100 at most. This method really is not the right tool for this task. – Sebastian Simon Jan 20 '23 at 18:38
  • @SebastianSimon Fair enough. These are here better solutions if you need a high number of repetitions – Jose Rui Santos Jan 20 '23 at 20:32
4

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;
};
csharpfolk
  • 4,124
  • 25
  • 31
  • Why do you say "interesting way"? what is so interesting here? it's the obvious go-to solution, the most basic fundamental example of a computer program. – vsync Sep 19 '18 at 11:10
2

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.

Ezequiel García
  • 2,616
  • 19
  • 12
2
function repeatString(n, string) {
  var repeat = [];
  repeat.length = n + 1;
  return repeat.join(string);
}

repeatString(3,'x'); // => xxx
repeatString(10,''); // => ""
alejandro
  • 2,799
  • 1
  • 17
  • 25
2

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

using Typescript and arrow fun

const repeatString = (str: string, num: number) => num > 0 ? 
 Array(num+1).join(str) : "";

console.log(repeatString("",10))
//outputs: 

function repeatString(str, num) {
  // Array(num+1) is the string you want to repeat and the times to repeat the string
  return num > 0 ? Array(num+1).join(str) : "";
}

console.log(repeatString("a",10))
// outputs: aaaaaaaaaa
console.log(repeatString("",10))
//outputs: 
Amir Danish
  • 418
  • 5
  • 8
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('');
    }
Koushik Das
  • 9,678
  • 3
  • 51
  • 50
1

I realize that it's not a popular task, what if you need to repeat your string not an integer number of times?

It's possible with repeat() and slice(), here's how:

String.prototype.fracRepeat = function(n){
  if(n < 0) n = 0;
  var n_int = ~~n; // amount of whole times to repeat
  var n_frac = n - n_int; // amount of fraction times (e.g., 0.5)
  var frac_length = ~~(n_frac * this.length); // length in characters of fraction part, floored
  
  return this.repeat(n) + this.slice(0, frac_length);
}

And below a shortened version:

String.prototype.fracRepeat = function(n){
   if(n < 0) n = 0;
   return this.repeat(n) + this.slice(0, ~~((n - ~~n) * this.length));
}

var s = "abcd";
console.log(s.fracRepeat(2.5))
nicael
  • 18,550
  • 13
  • 57
  • 90
0

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.

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

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

Community
  • 1
  • 1
Bruno Bronosky
  • 66,273
  • 12
  • 162
  • 149
0

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);
0x4a6f4672
  • 27,297
  • 17
  • 103
  • 140
0
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);
jwpfox
  • 5,124
  • 11
  • 45
  • 42
Filth
  • 3,116
  • 14
  • 51
  • 79
0

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;
}
Sarsaparilla
  • 6,300
  • 1
  • 32
  • 21
0

In CoffeeScript:

( 'a' for dot in [0..10]).join('')
-1
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"
Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140