diff options
| author | Florian Merz <me@fiji-flo.de> | 2021-02-11 14:46:50 +0100 |
|---|---|---|
| committer | Florian Merz <me@fiji-flo.de> | 2021-02-11 14:46:50 +0100 |
| commit | a55b575e8089ee6cab7c5c262a7e6db55d0e34d6 (patch) | |
| tree | 5032e6779a402a863654c9d65965073f09ea4182 /files/es/web/javascript/reference/global_objects/string/matchall | |
| parent | 8260a606c143e6b55a467edf017a56bdcd6cba7e (diff) | |
| download | translated-content-a55b575e8089ee6cab7c5c262a7e6db55d0e34d6.tar.gz translated-content-a55b575e8089ee6cab7c5c262a7e6db55d0e34d6.tar.bz2 translated-content-a55b575e8089ee6cab7c5c262a7e6db55d0e34d6.zip | |
unslug es: move
Diffstat (limited to 'files/es/web/javascript/reference/global_objects/string/matchall')
| -rw-r--r-- | files/es/web/javascript/reference/global_objects/string/matchall/index.html | 134 |
1 files changed, 134 insertions, 0 deletions
diff --git a/files/es/web/javascript/reference/global_objects/string/matchall/index.html b/files/es/web/javascript/reference/global_objects/string/matchall/index.html new file mode 100644 index 0000000000..a536720dbd --- /dev/null +++ b/files/es/web/javascript/reference/global_objects/string/matchall/index.html @@ -0,0 +1,134 @@ +--- +title: String.prototype.matchAll() +slug: Web/JavaScript/Referencia/Objetos_globales/String/matchAll +tags: + - Cadena + - Expresiones Regulares + - JavaScript + - Prototipo + - Referencia + - metodo +translation_of: Web/JavaScript/Reference/Global_Objects/String/matchAll +--- +<div>{{JSRef}}</div> + +<p>El método <strong><code>matchAll()</code></strong> retorna un iterador de todos los resultados de ocurrencia en una <em>cadena de texto</em> contra una expresión regular, incluyendo grupos de captura.</p> + +<div>{{EmbedInteractiveExample("pages/js/string-matchall.html")}}</div> + + + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox"><var>cadena</var>.matchAll(<var>expresionRegular</var>)</pre> + +<h3 id="Parámetros">Parámetros</h3> + +<dl> + <dt><var>expresionRegular</var></dt> + <dd>Un objeto expresión regular. Si se pasa un objeto no-RegExp <code>obj</code>, este es implícitamente convertido a {{jsxref("RegExp")}} vía <code>new RegExp(obj)</code>.</dd> +</dl> + +<h3 id="Valor_devuelto">Valor devuelto</h3> + +<p>Un <a href="/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators">iterador</a> (el cual no es reiniciable).</p> + +<h2 id="Ejemplo">Ejemplo</h2> + +<h3 id="Regexp.exec()_y_matchAll()">Regexp.exec() y matchAll()</h3> + +<p>Antes de la adición de <code>matchAll</code> a JavaScript, fue posible hacer llamados a <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec">regexp.exec</a> (y usar expresiones regulares con la bandera <code>/g</code>) en un ciclo para obtener las ocurrencias:</p> + +<pre class="brush: js">const regexp = RegExp('foo[a-z]*','g'); +const cadena = 'mesa football, foosball'; +let ocurrencia; + +while ((ocurrencia = regexp.exec(cadena)) !== null) { + console.log(`Encontrado ${ocurrencia[0]} inicio=${ocurrencia.index} final=${regexp.lastIndex}.`); + // salida esperada: "Encontrado football inicio=5 final=13." + // salida esperada: "Encontrado foosball inicio=15 final=23." +}</pre> + +<p>Con <code>matchAll</code> disponible, puedes evitar el ciclo <code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/while">while</a></code> y <code>exec</code> con <code>/g</code>. Por el contrario, usando <code>matchAll</code>, obtienes un iterador con el cual puedes usar con constructores más convenientes <code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/for...of">for...of</a></code>, <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax">array spread</a>, o {{jsxref("Array.from()")}}:</p> + +<pre class="brush: js">const regexp = RegExp('foo[a-z]*','g'); +const cadena = 'mesa football, foosball'; +const ocurrencias = cadena.matchAll(regexp); + +for (const ocurrencia of ocurrencias) { + console.log(`Encontrado ${ocurrencia[0]} inicio=${ocurrencia.index} final=${ocurrencia.index + ocurrencia[0].length}.`); +} +// salida esperada: "Encontrado football start=5 end=13." +// salida esperada: "Encontrado foosball start=15 end=23." + +// el iterador ocurrencias es agotado después de la iteración for..of +// Llama matchAll de nuevo para crear un nuevo iterador +Array.from(cadena.matchAll(regexp), m => m[0]); +// Array [ "football", "foosball" ]</pre> + +<p><code>matchAll</code> solo devuelve la primer ocurrencia si la bandera <code>/g</code> está ausente.</p> + +<pre class="brush: js">const regexp = RegExp('[a-c]',''); +const cadena = 'abc'; +Array.from(cadena.matchAll(regexp), m => m[0]); +// Array [ "a" ] +</pre> + +<p><code>matchAll</code> internamente hace un clon de la expresión regular, entonces a diferencia de <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec">regexp.exec</a>, <code>lastIndex</code> no cambia a medida que la cadena es escaneada.</p> + +<pre class="brush: js">const regexp = RegExp('[a-c]','g'); +regexp.lastIndex = 1; +const cadena = 'abc'; +Array.from(cadena.matchAll(regexp), m => `${regexp.lastIndex} ${m[0]}`); +// Array [ "1 b", "1 c" ]</pre> + +<h3 id="Mejor_acceso_para_capturar_grupos">Mejor acceso para capturar grupos</h3> + +<p>Otra buena razón para <code>matchAll</code> es el mejorado acceso a los grupos de captura. Los grupos de captura son ignorados cuando se usa <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match">match()</a></code> con la bandera global <code>/g</code>:</p> + +<pre class="brush: js">var regexp = /t(e)(st(\d?))/g; +var cadena = 'test1test2'; + +cadena.match(regexp); +// Array ['test1', 'test2']</pre> + +<p>Con <code>matchAll</code> puedes acceder a ellos:</p> + +<pre class="brush: js">let array = [...str.matchAll(regexp)]; + +array[0]; +// ['test1', 'e', 'st1', '1', index: 0, input: 'test1test2', length: 4] +array[1]; +// ['test2', 'e', 'st2', '2', index: 5, input: 'test1test2', length: 4] +</pre> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-string.prototype.matchall', 'String.prototype.matchAll')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_de_navegadores">Compatibilidad de navegadores</h2> + +<p class="hidden">The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.String.matchAll")}}</p> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li>{{jsxref("RegExp")}}</li> + <li>{{jsxref("RegExp.prototype.exec()")}}</li> + <li>{{jsxref("RegExp.prototype.test()")}}</li> +</ul> |
