|
1 |
| -# Patterns and flags |
| 1 | +# Patrones y banderas (flags) |
2 | 2 |
|
3 |
| -Regular expressions are patterns that provide a powerful way to search and replace in text. |
| 3 | +Las expresiones regulares son patrones que proporcionan una forma poderosa de buscar y reemplazar texto. |
4 | 4 |
|
5 |
| -In JavaScript, they are available via the [RegExp](mdn:js/RegExp) object, as well as being integrated in methods of strings. |
| 5 | +En JavaScript, están disponibles a través del objeto [RegExp](mdn:js/RegExp), además de integrarse en métodos de cadenas. |
6 | 6 |
|
7 |
| -## Regular Expressions |
| 7 | +## Expresiones Regulares |
8 | 8 |
|
9 |
| -A regular expression (also "regexp", or just "reg") consists of a *pattern* and optional *flags*. |
| 9 | +Una expresión regular (también "regexp", o simplemente "reg") consiste en un *patrón* y *banderas* opcionales. |
10 | 10 |
|
11 |
| -There are two syntaxes that can be used to create a regular expression object. |
12 | 11 |
|
13 |
| -The "long" syntax: |
| 12 | +Hay dos sintaxis que se pueden usar para crear un objeto de expresión regular. |
| 13 | + |
| 14 | +La sintaxis "larga": |
14 | 15 |
|
15 | 16 | ```js
|
16 |
| -regexp = new RegExp("pattern", "flags"); |
| 17 | +regexp = new RegExp("patrón", "banderas"); |
17 | 18 | ```
|
18 | 19 |
|
19 |
| -And the "short" one, using slashes `"/"`: |
| 20 | +Y el "corto", usando barras `"/"`: |
20 | 21 |
|
21 | 22 | ```js
|
22 |
| -regexp = /pattern/; // no flags |
23 |
| -regexp = /pattern/gmi; // with flags g,m and i (to be covered soon) |
| 23 | +regexp = /pattern/; // sin banderas |
| 24 | +regexp = /pattern/gmi; // con banderas g,m e i (para ser cubierto pronto) |
24 | 25 | ```
|
25 | 26 |
|
26 |
| -Slashes `pattern:/.../` tell JavaScript that we are creating a regular expression. They play the same role as quotes for strings. |
| 27 | +Las barras `pattern:/.../` le dicen a JavaScript que estamos creando una expresión regular. Juegan el mismo papel que las comillas para las cadenas. |
27 | 28 |
|
28 |
| -In both cases `regexp` becomes an instance of the built-in `RegExp` class. |
| 29 | +En ambos casos, `regexp` se convierte en una instancia de la clase incorporada `RegExp`. |
29 | 30 |
|
30 |
| -The main difference between these two syntaxes is that pattern using slashes `/.../` does not allow for expressions to be inserted (like string template literals with `${...}`). They are fully static. |
| 31 | +La principal diferencia entre estas dos sintaxis es que el patrón que utiliza barras `/.../` no permite que se inserten expresiones (como los literales de plantilla de cadena con `${...}`). Son completamente estáticos. |
31 | 32 |
|
32 |
| -Slashes are used when we know the regular expression at the code writing time -- and that's the most common situation. While `new RegExp`, is more often used when we need to create a regexp "on the fly" from a dynamically generated string. For instance: |
| 33 | +Las barras se utilizan cuando conocemos la expresión regular en el momento de escribir el código, y esa es la situación más común. Mientras que `new RegExp`, se usa con mayor frecuencia cuando necesitamos crear una expresión regular "sobre la marcha" a partir de una cadena generada dinámicamente. Por ejemplo: |
33 | 34 |
|
34 | 35 | ```js
|
35 |
| -let tag = prompt("What tag do you want to find?", "h2"); |
| 36 | +let tag = prompt("¿Qué etiqueta quieres encontrar?", "h2"); |
36 | 37 |
|
37 |
| -let regexp = new RegExp(`<${tag}>`); // same as /<h2>/ if answered "h2" in the prompt above |
| 38 | +igual que /<h2>/ si respondió "h2" en el mensaje anterior |
38 | 39 | ```
|
39 | 40 |
|
40 |
| -## Flags |
| 41 | +## Banderas |
41 | 42 |
|
42 |
| -Regular expressions may have flags that affect the search. |
| 43 | +Las expresiones regulares pueden usar banderas que afectan la búsqueda. |
43 | 44 |
|
44 |
| -There are only 6 of them in JavaScript: |
| 45 | +Solo hay 6 de ellas en JavaScript: |
45 | 46 |
|
46 | 47 | `pattern:i`
|
47 |
| -: With this flag the search is case-insensitive: no difference between `A` and `a` (see the example below). |
| 48 | +: Con esta bandera, la búsqueda no distingue entre mayúsculas y minúsculas: no hay diferencia entre `A` y `a` (consulte el ejemplo a continuación). |
48 | 49 |
|
49 | 50 | `pattern:g`
|
50 |
| -: With this flag the search looks for all matches, without it -- only the first match is returned. |
| 51 | +: Con esta bandera, la búsqueda encuentra todas las coincidencias, sin ella, solo se devuelve la primera coincidencia. |
51 | 52 |
|
52 | 53 | `pattern:m`
|
53 |
| -: Multiline mode (covered in the chapter <info:regexp-multiline-mode>). |
| 54 | +: Modo multilínea (cubierto en el capítulo <info:regexp-multiline-mode>). |
54 | 55 |
|
55 | 56 | `pattern:s`
|
56 |
| -: Enables "dotall" mode, that allows a dot `pattern:.` to match newline character `\n` (covered in the chapter <info:regexp-character-classes>). |
| 57 | +: Habilita el modo "dotall", que permite que un punto `pattern:.` coincida con el carácter de línea nueva `\n` (cubierto en el capítulo <info:regexp-character-classes>). |
| 58 | + |
57 | 59 |
|
58 | 60 | `pattern:u`
|
59 |
| -: Enables full unicode support. The flag enables correct processing of surrogate pairs. More about that in the chapter <info:regexp-unicode>. |
| 61 | +: Permite el soporte completo de Unicode. La bandera permite el procesamiento correcto de pares sustitutos. Más del tema en el capítulo <info:regexp-unicode>. |
60 | 62 |
|
61 | 63 | `pattern:y`
|
62 |
| -: "Sticky" mode: searching at the exact position in the text (covered in the chapter <info:regexp-sticky>) |
| 64 | +: Modo "adhesivo": búsqueda en la posición exacta del texto (cubierto en el capítulo <info:regexp-sticky>) |
63 | 65 |
|
64 |
| -```smart header="Colors" |
65 |
| -From here on the color scheme is: |
| 66 | +```smart header="Colores" |
| 67 | +A partir de aquí, el esquema de color es: |
66 | 68 |
|
67 | 69 | - regexp -- `pattern:red`
|
68 |
| -- string (where we search) -- `subject:blue` |
69 |
| -- result -- `match:green` |
| 70 | +- cadena (donde buscamos) -- `subject:blue` |
| 71 | +- resulta -- `match:green` |
70 | 72 | ```
|
71 | 73 |
|
72 |
| -## Searching: str.match |
| 74 | +## Buscando: str.match |
73 | 75 |
|
74 |
| -As mentioned previously, regular expressions are integrated with string methods. |
| 76 | +Como se mencionó anteriormente, las expresiones regulares se integran con los métodos de cadena. |
75 | 77 |
|
76 |
| -The method `str.match(regexp)` finds all matches of `regexp` in the string `str`. |
| 78 | +El método `str.match(regex)` busca todas las coincidencias de `regex` en la cadena `str`. |
77 | 79 |
|
78 |
| -It has 3 working modes: |
| 80 | +Tiene 3 modos de trabajo: |
79 | 81 |
|
80 |
| -1. If the regular expression has flag `pattern:g`, it returns an array of all matches: |
| 82 | +1. Si la expresión regular tiene la bandera `pattern:g`, devuelve un arreglo de todas las coincidencias: |
81 | 83 | ```js run
|
82 | 84 | let str = "We will, we will rock you";
|
83 | 85 |
|
84 |
| - alert( str.match(/we/gi) ); // We,we (an array of 2 substrings that match) |
| 86 | + alert( str.match(/we/gi) ); // We,we (un arreglo de 2 subcadenas que coinciden) |
85 | 87 | ```
|
86 |
| - Please note that both `match:We` and `match:we` are found, because flag `pattern:i` makes the regular expression case-insensitive. |
| 88 | + Tenga en cuenta que tanto `match:We` como `match: we` se encuentran, porque la bandera `pattern:i` hace que la expresión regular no distinga entre mayúsculas y minúsculas. |
87 | 89 |
|
88 |
| -2. If there's no such flag it returns only the first match in the form of an array, with the full match at index `0` and some additional details in properties: |
| 90 | +2. Si no existe dicha bandera, solo devuelve la primera coincidencia en forma de arreglo, con la coincidencia completa en el índice `0` y algunos detalles adicionales en las propiedades: |
89 | 91 | ```js run
|
90 | 92 | let str = "We will, we will rock you";
|
91 | 93 |
|
92 |
| - let result = str.match(/we/i); // without flag g |
| 94 | + let result = str.match(/we/i); // sin la bandera g |
93 | 95 |
|
94 |
| - alert( result[0] ); // We (1st match) |
| 96 | + alert( result[0] ); // We (1ra coincidencia) |
95 | 97 | alert( result.length ); // 1
|
96 | 98 |
|
97 |
| - // Details: |
98 |
| - alert( result.index ); // 0 (position of the match) |
99 |
| - alert( result.input ); // We will, we will rock you (source string) |
| 99 | + // Detalles: |
| 100 | + alert( result.index ); // 0 (posición de la coincidencia) |
| 101 | + alert( result.input ); // We will, we will rock you (cadena fuente) |
100 | 102 | ```
|
101 |
| - The array may have other indexes, besides `0` if a part of the regular expression is enclosed in parentheses. We'll cover that in the chapter <info:regexp-groups>. |
| 103 | + El arreglo puede tener otros índices, además de `0` si una parte de la expresión regular está encerrada entre paréntesis. Cubriremos eso en el capítulo <info:regexp-groups>. |
102 | 104 |
|
103 |
| -3. And, finally, if there are no matches, `null` is returned (doesn't matter if there's flag `pattern:g` or not). |
| 105 | +3. Y, finalmente, si no hay coincidencias, se devuelve `null` (no importa si hay una bandera `pattern:g` o no). |
104 | 106 |
|
105 |
| - This a very important nuance. If there are no matches, we don't receive an empty array, but instead receive `null`. Forgetting about that may lead to errors, e.g.: |
| 107 | + Este es un matiz muy importante. Si no hay coincidencias, no recibimos un arreglo vacío, sino que recibimos `null`. Olvidar eso puede conducir a errores, por ejemplo: |
106 | 108 |
|
107 | 109 | ```js run
|
108 | 110 | let matches = "JavaScript".match(/HTML/); // = null
|
109 | 111 |
|
110 |
| - if (!matches.length) { // Error: Cannot read property 'length' of null |
111 |
| - alert("Error in the line above"); |
| 112 | + if (!matches.length) { // Error: No se puede leer la propiedad 'length' de null |
| 113 | + alert("Error en la línea anterior"); |
112 | 114 | }
|
113 | 115 | ```
|
114 | 116 |
|
115 |
| - If we'd like the result to always be an array, we can write it this way: |
| 117 | + Si queremos que el resultado sea siempre un arreglo, podemos escribirlo de esta manera: |
116 | 118 |
|
117 | 119 | ```js run
|
118 | 120 | let matches = "JavaScript".match(/HTML/)*!* || []*/!*;
|
119 | 121 |
|
120 | 122 | if (!matches.length) {
|
121 |
| - alert("No matches"); // now it works |
| 123 | + alert("Sin coincidencias"); // ahora si trabaja |
122 | 124 | }
|
123 | 125 | ```
|
124 | 126 |
|
125 |
| -## Replacing: str.replace |
| 127 | +## Reemplazando: str.replace |
126 | 128 |
|
127 |
| -The method `str.replace(regexp, replacement)` replaces matches found using `regexp` in string `str` with `replacement` (all matches if there's flag `pattern:g`, otherwise, only the first one). |
| 129 | +El método `str.replace(regexp, replacement)` reemplaza las coincidencias encontradas usando `regexp` en la cadena `str` con `replacement` (todas las coincidencias si está la bandera `pattern:g`, de lo contrario, solo la primera). |
128 | 130 |
|
129 |
| -For instance: |
| 131 | +Por ejemplo: |
130 | 132 |
|
131 | 133 | ```js run
|
132 |
| -// no flag g |
| 134 | +// sin la bandera g |
133 | 135 | alert( "We will, we will".replace(/we/i, "I") ); // I will, we will
|
134 | 136 |
|
135 |
| -// with flag g |
| 137 | +// con la bandera g |
136 | 138 | alert( "We will, we will".replace(/we/ig, "I") ); // I will, I will
|
137 | 139 | ```
|
138 | 140 |
|
139 |
| -The second argument is the `replacement` string. We can use special character combinations in it to insert fragments of the match: |
| 141 | +El segundo argumento es la cadena de `replacement`. Podemos usar combinaciones de caracteres especiales para insertar fragmentos de la coincidencia: |
140 | 142 |
|
141 |
| -| Symbols | Action in the replacement string | |
| 143 | +| Símbolos | Acción en la cadena de reemplazo | |
142 | 144 | |--------|--------|
|
143 |
| -|`$&`|inserts the whole match| |
144 |
| -|<code>$`</code>|inserts a part of the string before the match| |
145 |
| -|`$'`|inserts a part of the string after the match| |
146 |
| -|`$n`|if `n` is a 1-2 digit number, then it inserts the contents of n-th parentheses, more about it in the chapter <info:regexp-groups>| |
147 |
| -|`$<name>`|inserts the contents of the parentheses with the given `name`, more about it in the chapter <info:regexp-groups>| |
148 |
| -|`$$`|inserts character `$` | |
| 145 | +|`$&`|inserta toda la coincidencia| |
| 146 | +|<code>$`</code>|inserta una parte de la cadena antes de la coincidencia| |
| 147 | +|`$'`|inserta una parte de la cadena después de la coincidencia| |
| 148 | +|`$n`|si `n` es un número de 1-2 dígitos, entonces inserta el contenido de los paréntesis n-ésimo, más del tema en el capítulo <info:regexp-groups>| |
| 149 | +|`$<name>`|inserta el contenido de los paréntesis con el `nombre` dado, más del tema en el capítulo <info:regexp-groups>| |
| 150 | +|`$$`|inserta el carácter `$` | |
149 | 151 |
|
150 |
| -An example with `pattern:$&`: |
| 152 | +Un ejemplo con `pattern:$&`: |
151 | 153 |
|
152 | 154 | ```js run
|
153 |
| -alert( "I love HTML".replace(/HTML/, "$& and JavaScript") ); // I love HTML and JavaScript |
| 155 | +alert( "Me gusta HTML".replace(/HTML/, "$& y JavaScript") ); // Me gusta HTML y JavaScript |
154 | 156 | ```
|
155 | 157 |
|
156 |
| -## Testing: regexp.test |
| 158 | +## Pruebas: regexp.test |
157 | 159 |
|
158 |
| -The method `regexp.test(str)` looks for at least one match, if found, returns `true`, otherwise `false`. |
| 160 | +El método `regexp.test(str)` busca al menos una coincidencia, si se encuentra, devuelve `true`, de lo contrario `false`. |
159 | 161 |
|
160 | 162 | ```js run
|
161 |
| -let str = "I love JavaScript"; |
162 |
| -let regexp = /LOVE/i; |
| 163 | +let str = "Me gusta JavaScript"; |
| 164 | +let regexp = /GUSTA/i; |
| 165 | +
|
163 | 166 |
|
164 | 167 | alert( regexp.test(str) ); // true
|
165 | 168 | ```
|
166 | 169 |
|
167 |
| -Later in this chapter we'll study more regular expressions, walk through more examples, and also meet other methods. |
| 170 | +Más adelante en este capítulo estudiaremos más expresiones regulares, exploraremos más ejemplos y también conoceremos otros métodos. |
168 | 171 |
|
169 |
| -Full information about the methods is given in the article <info:regexp-methods>. |
| 172 | +La información completa sobre métodos se proporciona en el artículo <info:regexp-method>. |
170 | 173 |
|
171 |
| -## Summary |
| 174 | +## Resumen |
172 | 175 |
|
173 |
| -- A regular expression consists of a pattern and optional flags: `pattern:g`, `pattern:i`, `pattern:m`, `pattern:u`, `pattern:s`, `pattern:y`. |
174 |
| -- Without flags and special symbols (that we'll study later), the search by a regexp is the same as a substring search. |
175 |
| -- The method `str.match(regexp)` looks for matches: all of them if there's `pattern:g` flag, otherwise, only the first one. |
176 |
| -- The method `str.replace(regexp, replacement)` replaces matches found using `regexp` with `replacement`: all of them if there's `pattern:g` flag, otherwise only the first one. |
177 |
| -- The method `regexp.test(str)` returns `true` if there's at least one match, otherwise, it returns `false`. |
| 176 | +- Una expresión regular consiste en un patrón y banderas opcionales: `pattern:g`, `pattern:i`, `pattern:m`, `pattern:u`, `pattern:s`, `pattern:y`. |
| 177 | +- Sin banderas y símbolos especiales (que estudiaremos más adelante), la búsqueda por expresión regular es lo mismo que una búsqueda de subcadena. |
| 178 | +- El método `str.match(regexp)` busca coincidencias: devuelve todas si hay una bandera `pattern:g`, de lo contrario, solo la primera. |
| 179 | +- El método `str.replace(regexp, replacement)` reemplaza las coincidencias encontradas usando `regexp` con `replacement`: devuelve todas si hay una bandera `pattern:g`, de lo contrario solo la primera. |
| 180 | +- El método `regexp.test(str)` devuelve `true` si hay al menos una coincidencia, de lo contrario, devuelve `false`. |
0 commit comments