Skip to content

Commit 8ed429d

Browse files
authored
Merge pull request #284 from cortizg/es.javascript.info.9-07-e
Escaping, special characters
2 parents 00bb7fa + 8f21d97 commit 8ed429d

File tree

1 file changed

+37
-37
lines changed
  • 9-regular-expressions/07-regexp-escaping

1 file changed

+37
-37
lines changed
Lines changed: 37 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -1,99 +1,99 @@
11

2-
# Escaping, special characters
2+
# Escapando, caracteres especiales
33

4-
As we've seen, a backslash `pattern:\` is used to denote character classes, e.g. `pattern:\d`. So it's a special character in regexps (just like in regular strings).
4+
Como hemos visto, una barra invertida `pattern:\` se usa para denotar clases de caracteres, p.ej. `pattern:\d`. Por lo tanto, es un carácter especial en expresiones regulares (al igual que en las cadenas regulares).
55

6-
There are other special characters as well, that have special meaning in a regexp. They are used to do more powerful searches. Here's a full list of them: `pattern:[ \ ^ $ . | ? * + ( )`.
6+
También hay otros caracteres especiales que tienen un significado especial en una expresión regular. Se utilizan para hacer búsquedas más potentes. Aquí hay una lista completa de ellos: `pattern:[ \ ^ $ . | ? * + ( )`.
77

8-
Don't try to remember the list -- soon we'll deal with each of them separately and you'll know them by heart automatically.
8+
No intentes recordar la lista: pronto nos ocuparemos de cada uno de ellos por separado y los recordarás fácilmente.
99

10-
## Escaping
10+
## Escapando
1111

12-
Let's say we want to find literally a dot. Not "any character", but just a dot.
12+
Digamos que queremos encontrar literalmente un punto. No "cualquier carácter", sino solo un punto.
1313

14-
To use a special character as a regular one, prepend it with a backslash: `pattern:\.`.
14+
Para usar un carácter especial como uno normal, agrégalo con una barra invertida: `pattern:\.`.
1515

16-
That's also called "escaping a character".
16+
A esto se le llama "escape de carácter".
1717

18-
For example:
18+
Por ejemplo:
1919
```js run
20-
alert( "Chapter 5.1".match(/\d\.\d/) ); // 5.1 (match!)
21-
alert( "Chapter 511".match(/\d\.\d/) ); // null (looking for a real dot \.)
20+
alert( "Capítulo 5.1".match(/\d\.\d/) ); // 5.1 (¡Coincide!)
21+
alert( "Capítulo 511".match(/\d\.\d/) ); // null (buscando un punto real \.)
2222
```
2323

24-
Parentheses are also special characters, so if we want them, we should use `pattern:\(`. The example below looks for a string `"g()"`:
24+
Los paréntesis también son caracteres especiales, por lo que si los buscamos, deberíamos usar `pattern:\(`. El siguiente ejemplo busca una cadena `"g()"`:
2525

2626
```js run
27-
alert( "function g()".match(/g\(\)/) ); // "g()"
27+
alert( "función g()".match(/g\(\)/) ); // "g()"
2828
```
2929

30-
If we're looking for a backslash `\`, it's a special character in both regular strings and regexps, so we should double it.
30+
Si estamos buscando una barra invertida `\`, como es un carácter especial tanto en cadenas regulares como en expresiones regulares, debemos duplicarlo.
3131

3232
```js run
3333
alert( "1\\2".match(/\\/) ); // '\'
3434
```
3535

36-
## A slash
36+
## Una barra
3737

38-
A slash symbol `'/'` is not a special character, but in JavaScript it is used to open and close the regexp: `pattern:/...pattern.../`, so we should escape it too.
38+
Un símbolo de barra `'/'` no es un carácter especial, pero en JavaScript se usa para abrir y cerrar expresiones regulares: `pattern:/...pattern.../`, por lo que también debemos escaparlo.
3939

40-
Here's what a search for a slash `'/'` looks like:
40+
Así es como se ve la búsqueda de una barra `'/'`:
4141

4242
```js run
4343
alert( "/".match(/\//) ); // '/'
4444
```
4545

46-
On the other hand, if we're not using `pattern:/.../`, but create a regexp using `new RegExp`, then we don't need to escape it:
46+
Por otro lado, si no estamos usando `pattern:/.../`, pero creamos una expresión regular usando `new RegExp`, entonces no necesitamos escaparla:
4747

4848
```js run
49-
alert( "/".match(new RegExp("/")) ); // finds /
49+
alert( "/".match(new RegExp("/")) ); // encuentra /
5050
```
5151

5252
## new RegExp
5353

54-
If we are creating a regular expression with `new RegExp`, then we don't have to escape `/`, but need to do some other escaping.
54+
Si estamos creando una expresión regular con `new RegExp`, entonces no tenemos que escapar la barra `/`, pero sí otros caracteres especiales.
5555

56-
For instance, consider this:
56+
Por ejemplo, considere esto:
5757

5858
```js run
5959
let regexp = new RegExp("\d\.\d");
6060

61-
alert( "Chapter 5.1".match(regexp) ); // null
61+
alert( "Capítulo 5.1".match(regexp) ); // null
6262
```
6363

64-
The similar search in one of previous examples worked with `pattern:/\d\.\d/`, but `new RegExp("\d\.\d")` doesn't work, why?
64+
En uno de los ejemplos anteriores funcionó la búsqueda con `pattern:/\d\.\d/`, pero `new RegExp ("\d\.\d")` no funciona, ¿por qué?
6565

66-
The reason is that backslashes are "consumed" by a string. As we may recall, regular strings have their own special characters, such as `\n`, and a backslash is used for escaping.
66+
La razón es que las barras invertidas son "consumidas" por una cadena. Como podemos recordar, las cadenas regulares tienen sus propios caracteres especiales, como `\n`, y se usa una barra invertida para escapar esos caracteres especiales de cadena.
6767

68-
Here's how "\d\.\d" is preceived:
68+
Así es como se percibe "\d\.\d\":
6969

7070
```js run
7171
alert("\d\.\d"); // d.d
7272
```
7373

74-
String quotes "consume" backslashes and interpret them on their own, for instance:
74+
Las comillas de cadenas "consumen" barras invertidas y las interpretan como propias, por ejemplo:
7575

76-
- `\n` -- becomes a newline character,
77-
- `\u1234` -- becomes the Unicode character with such code,
78-
- ...And when there's no special meaning: like `pattern:\d` or `\z`, then the backslash is simply removed.
76+
- `\n` -- se convierte en un carácter de línea nueva,
77+
- `\u1234` -- se convierte en el carácter Unicode con dicho código,
78+
- ...Y cuando no hay un significado especial: como `pattern:\d` o `\z`, entonces la barra invertida simplemente se elimina.
7979

80-
So `new RegExp` gets a string without backslashes. That's why the search doesn't work!
80+
Así que `new RegExp` toma una cadena sin barras invertidas. ¡Por eso la búsqueda no funciona!
8181

82-
To fix it, we need to double backslashes, because string quotes turn `\\` into `\`:
82+
Para solucionarlo, debemos duplicar las barras invertidas, porque las comillas de cadena convierten `\\` en `\`:
8383

8484
```js run
8585
*!*
8686
let regStr = "\\d\\.\\d";
8787
*/!*
88-
alert(regStr); // \d\.\d (correct now)
88+
alert(regStr); // \d\.\d (ahora está correcto)
8989

9090
let regexp = new RegExp(regStr);
9191

92-
alert( "Chapter 5.1".match(regexp) ); // 5.1
92+
alert( "Capítulo 5.1".match(regexp) ); // 5.1
9393
```
9494

95-
## Summary
95+
## Resumen
9696

97-
- To search for special characters `pattern:[ \ ^ $ . | ? * + ( )` literally, we need to prepend them with a backslash `\` ("escape them").
98-
- We also need to escape `/` if we're inside `pattern:/.../` (but not inside `new RegExp`).
99-
- When passing a string `new RegExp`, we need to double backslashes `\\`, cause string quotes consume one of them.
97+
- Para buscar literalmente caracteres especiales `pattern:[ \ ^ $ . | ? * + ( )`, se les antepone una barra invertida `\` ("escaparlos").
98+
- Se debe escapar `/` si estamos dentro de `pattern:/.../` (pero no dentro de `new RegExp`).
99+
- Al pasar una cadena a `new RegExp`, se deben duplicar las barras invertidas `\\`, porque las comillas de cadena consumen una.

0 commit comments

Comments
 (0)