Repeat Character N Times

javascript repeat function n times
java repeat character n times
js repeat array
repeated letters in words javascript
string repeat c#
javascript substring
java create string of repeated characters
javascript replace

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.

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:


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 jsperf, 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).

String.prototype.repeat(), This JavaScript tutorial explains how to use the string method called repeat() with is a string method that is used to repeat a string a specified number of times. String repeat () – Repeat string N times in Java By Lokesh Gupta | Filed Under: Java 11 Learn to repeat a given string N times, to produce a new string which contains all the repetitions, though a simple Java program. We will use method Sting.repeat (N) (since Java 11) and using regular expression which can be used till Java 10.

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

JavaScript: String repeat() method, Learn to repeat a given string N times, to produce a new string which contains all the repetitions String repeated = new String( new char [ 3 ]).replace( "\0" , str);. How to repeat a character n times in a cell in Excel? Reuse Anything:Add the most used or complex formulas, charts and anything else to your favorites, and quickly reuse them More than 20 text features:Extract Number from Text String; Extract or Remove Part of Texts; Convert Numbers and Merge

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

String repeat() - Repeat string N times in Java, Parameter, Description. count, Required. The number of times the original string value should be repeated in the new string  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; }; share. Share a link to this answer.

The most performance-wice way is

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

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) {
      str += str;
    // Could we try:
    // return Array(count + 1).join(this);
    return rpt;

JavaScript String repeat() Method, This involves repeating a string a certain number of times. There are the three approaches I'll cover: using a while loop; using recursion; using  Simon also points out that according to this jsperf, 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).

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

Three ways to repeat a string in JavaScript, It is a sequence of variable-width characters where each and every character is represented by one or more bytes using UTF-8 Encoding. You are allowed to  The following example replicates a 0 character four times in front of a production line code in the AdventureWorks2012 database. SELECT [Name] , REPLICATE('0', 4) + [ProductLine] AS 'Line Code' FROM [Production].[Product] WHERE [ProductLine] = 'T' ORDER BY [Name]; GO Here is the result set.

Repeating a String for Specific Number of Times in Golang , This will duplicate a string or character N times to produce a new string. ERRE[​edit]. PROCEDURE REPEAT_STRING(S$,N%->REP$) LOCAL I  Print a character n times without using loop, recursion or goto in C++ Given a character c and a number n, print the character c, n times. We are not allowed to use loop, recursion and goto.

Repeat a string, count. The number of times to repeat repeatedValue in the resulting string. Creates a string containing the given character. init<S>(S). Creates a new string  The repeat() method returns a new string with a specified number of copies of the string it was called on. Browser Support The numbers in the table specify the first browser version that fully supports the method.

init(repeating:count:), I want to create a string which contains a single character repeated N times. The best I've come up with is this: (0..n).map({ |_| "X" }).collect::<Vec<_>>().concat(). Because asterisk is a special character in Powershell, you must use the escape character before it if you want it to be interpreted literally by Powershell: "`*"*35 BPK

  • Plus, you can use a variable instead of a fixed length - Array(20-len), say to pad a string up to 20.
  • 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("*")
  • This doesn't work in the 0 and 1 case, as they produce identical results.
  • The formula is Array(n+1).join("a"). When n=0, this returns the empty string, and when n=1, it returns "a". So I think it works in all cases.
  • @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.
  • It's a bad coding practice to pollute builtins' prototypes.
  • @nurettin see… for more discussion. I'd add a (properly scoped) static helper function, with a signature of repeat(str, n).
  • I'd remove the n= n || 1 part (or check if n is undefined), so you can also repeat 0 times.
  • Also have a look at Mozilla's official polyfill for ES6:…
  • @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. :)
  • This is a good one, but the new native "repeat" is even faster and needs no implementation, thanks anyway!
  • can you elaborate on the meaning of count >>>= 1, pattern += pattern;? what kind of statement is it?
  • So this is a polyfill for the native repeat, then? Just add an if (!String.prototype.repeat) { to the beginning and } to the end.