Repetir Carácter N Veces


En Perl puedo repetir un carácter varias veces usando la sintaxis:

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

¿Hay una forma sencilla de lograr esto en Javascript? Obviamente puedo usar una función, pero me preguntaba si había algún enfoque incorporado, o alguna otra técnica inteligente.

Author: John Slegers, 2009-12-10

21 answers

En estos días, el repeat el método string se implementa casi en todas partes. (Es no en Internet Explorer.) Así que a menos que necesite soportar navegadores más antiguos, simplemente puede escribir:

"a".repeat(10)

Antes de repeat, usamos este hack:

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

(Tenga en cuenta que un array de longitud 11 obtiene solo 10 "a"s, ya que Array.join pone el argumento entre los elementos del array.)

Simon también señala que de acuerdo con este jsperf, parece que es más rápido en Safari y Chrome (pero no Firefox) repetir un carácter varias veces simplemente añadiendo usando un bucle for (aunque un poco menos conciso).

 1025
Author: Jason Orendorff,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-31 14:21:15

En una nueva armonía ES6, tendrá una forma nativa de hacer esto con repeat. También ES6 en este momento solo experimental, esta característica es ya disponible en Edge, FF, Chrome y Safari

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

Y seguramente si la función de repetición no está disponible, puede usar old-good Array(n + 1).join("abc")

 292
Author: Salvador Dali,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-31 23:04:52

Conveniente si te repites mucho:

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)  )
 50
Author: kennebec,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-19 10:58:11

La manera más rendimiento-wice es https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/repeat

La versión corta está abajo.

  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 de 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;
  }
}
 13
Author: Konstantin Victorov,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-06-21 06:01:30

Una alternativa es:

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

Si necesita repetir varios caracteres, multiplique su condicional:

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

NOTA: No tienes que sobrepasar en 1 como con word = Array(11).join('a')

 11
Author: bonbon,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-04-25 06:42:58

Si no se opone a incluir una biblioteca en su proyecto, lodash tiene una función de repetición.

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

Https://lodash.com/docs#repeat

 10
Author: Nathan Danger,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-09-08 21:22:31

Para todos los navegadores

La siguiente función funcionará mucho más rápido que la opción sugerida en la respuesta aceptada:

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

Lo usarías así:

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

, Para comparar el desempeño de esta función con la de la opción propuesta en respuesta, ver este Violín y este Violín para los benchmarks.

Solo para navegadores modernos

En los navegadores modernos, ahora puede hacer esto usando String.prototype.repeat método:

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

Lea más sobre este método en MDN.

Esta opción es aún más rápida. Desafortunadamente, no funciona en ninguna versión de Internet Explorer. Los números de la tabla especifican la primera versión del navegador que soporta completamente el método:

introduzca la descripción de la imagen aquí

 9
Author: John Slegers,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-22 12:33:09
Array(10).fill('a').join('')

Aunque la respuesta más votada es un poco más compacta, con este enfoque no tiene que agregar un elemento de matriz adicional.

 8
Author: Grzegorz Pawlik,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-16 15:41:40

En ES2015 / ES6 puedes usar "*".repeat(n)

Así que simplemente agregue esto a sus proyectos, y estará listo.

  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()) 
    };
 7
Author: webdeb,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-02 20:44:30
/**  
 * 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"
);
 6
Author: yckart,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-10-14 12:11:27

Otra forma interesante de rápidamente repetir n carácter es utilizar la idea del algoritmo de exponenciación rápida:

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;
};
 5
Author: csharpfolk,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-01-06 12:17:45

Para repetir un valor en mis proyectos uso repetir

Por ejemplo:

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

Pero tenga cuidado porque este método se ha añadido a la especificación ECMAScript 6.

 2
Author: Ezequiel García,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-09 12:12:54

Esto es lo que uso:

function repeat(str, num) {
        var holder = [];
        for(var i=0; i<num; i++) {
            holder.push(str);
        }
        return holder.join('');
    }
 1
Author: Koushik Das,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-01-16 05:35:15
function repeatString(n, string) {
  var repeat = [];
  repeat.length = n + 1;
  return repeat.join(string);
}

repeatString(3,'x'); // => xxx
repeatString(10,''); // => ""
 1
Author: alejandro,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-03-16 03:35:36

Voy a ampliar la respuesta de@bonbon. Su método es una manera fácil de" anexar N caracteres a una cadena existente", en caso de que alguien necesite hacerlo. Por ejemplo, dado que "un google" es un 1 seguido de 100 ceros.

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>

NOTA: Tiene que agregar la longitud de la cadena original al condicional.

 0
Author: Bruno Bronosky,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 11:55:03

Lodash ofrece una funcionalidad similar a la función Javascript repeat() que no está disponible en todos los navegadores. Se llama _.repeat y disponible desde la versión 3.0.0:

_.repeat('a', 10);
 0
Author: 0x4a6f4672,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-12-13 17:23:02
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);
 0
Author: Filth,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-12-23 13:06:51

También se puede usar como un solo revestimiento:

function repeat(str, len) {
    while (str.length < len) str += str.substr(0, len-str.length);
    return str;
}
 0
Author: Hai Phan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-17 03:32:34

En CoffeeScript:

( 'a' for dot in [0..10]).join('')
 0
Author: David Mendez,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-06-01 13:03:42
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"
 -1
Author: Caglayan ALTINCI,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-10-24 07:59:31

Aquí hay una versión ES6

const repeat = (a,n) => Array(n).join(a+"|$|").split("|$|");
repeat("A",20).forEach((a,b) => console.log(a,b+1))
 -3
Author: Maxali,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-18 10:53:58