|
1 | | -# Unicode: flag "u" and class \p{...} |
| 1 | +# Unicode: bandera "u" y clase \p{...} |
2 | 2 |
|
3 | | -JavaScript uses [Unicode encoding](https://en.wikipedia.org/wiki/Unicode) for strings. Most characters are encoded with 2 bytes, but that allows to represent at most 65536 characters. |
| 3 | +JavaScript utiliza [codificación Unicode](https://en.wikipedia.org/wiki/Unicode) para las cadenas. La mayoría de los caracteres están codificados con 2 bytes, esto permite representar un máximo de 65536 caracteres. |
4 | 4 |
|
5 | | -That range is not big enough to encode all possible characters, that's why some rare characters are encoded with 4 bytes, for instance like `𝒳` (mathematical X) or `😄` (a smile), some hieroglyphs and so on. |
| 5 | +Ese rango no es lo suficientemente grande como para codificar todos los caracteres posibles, es por eso que algunos caracteres raros se codifican con 4 bytes, por ejemplo como `𝒳` (X matemática) o `😄` (una sonrisa), algunos sinogramas, etc. |
6 | 6 |
|
7 | | -Here are the unicode values of some characters: |
| 7 | +Aquí los valores unicode de algunos caracteres: |
8 | 8 |
|
9 | | -| Character | Unicode | Bytes count in unicode | |
| 9 | +| Carácter | Unicode | conteo de Bytes en unicode | |
10 | 10 | |------------|---------|--------| |
11 | 11 | | a | `0x0061` | 2 | |
12 | 12 | | ≈ | `0x2248` | 2 | |
13 | 13 | |𝒳| `0x1d4b3` | 4 | |
14 | 14 | |𝒴| `0x1d4b4` | 4 | |
15 | 15 | |😄| `0x1f604` | 4 | |
16 | 16 |
|
17 | | -So characters like `a` and `≈` occupy 2 bytes, while codes for `𝒳`, `𝒴` and `😄` are longer, they have 4 bytes. |
| 17 | +Entonces los caracteres como `a` e `≈` ocupan 2 bytes, mientras que los códigos para `𝒳`, `𝒴` y `😄` son más largos, tienen 4 bytes. |
18 | 18 |
|
19 | | -Long time ago, when JavaScript language was created, Unicode encoding was simpler: there were no 4-byte characters. So, some language features still handle them incorrectly. |
| 19 | +Hace mucho tiempo, cuando se creó el lenguaje JavaScript, la codificación Unicode era más simple: no había caracteres de 4 bytes. Por lo tanto, algunas características del lenguaje aún los manejan incorrectamente. |
20 | 20 |
|
21 | | -For instance, `length` thinks that here are two characters: |
| 21 | +Por ejemplo, aqui `length` interpreta que hay dos caracteres: |
22 | 22 |
|
23 | 23 | ```js run |
24 | 24 | alert('😄'.length); // 2 |
25 | 25 | alert('𝒳'.length); // 2 |
26 | 26 | ``` |
27 | 27 |
|
28 | | -...But we can see that there's only one, right? The point is that `length` treats 4 bytes as two 2-byte characters. That's incorrect, because they must be considered only together (so-called "surrogate pair", you can read about them in the article <info:string>). |
| 28 | +...Pero podemos ver que solo hay uno, ¿verdad? El punto es que `length` maneja 4 bytes como dos caracteres de 2 bytes. Eso es incorrecto, porque debe considerarse como uno solo (el llamado "par sustituto", puede leer sobre ellos en el artículo <info:string>). |
29 | 29 |
|
30 | | -By default, regular expressions also treat 4-byte "long characters" as a pair of 2-byte ones. And, as it happens with strings, that may lead to odd results. We'll see that a bit later, in the article <info:regexp-character-sets-and-ranges>. |
| 30 | +Por defecto, las expresiones regulares manejan los "caracteres largos" de 4 bytes como un par de caracteres de 2 bytes cada uno. Y, como sucede con las cadenas, eso puede conducir a resultados extraños. Lo veremos un poco más tarde, en el artículo <info:regexp-character-sets-and-range>. |
31 | 31 |
|
32 | | -Unlike strings, regular expressions have flag `pattern:u` that fixes such problems. With such flag, a regexp handles 4-byte characters correctly. And also Unicode property search becomes available, we'll get to it next. |
| 32 | +A diferencia de las cadenas, las expresiones regulares tienen la bandera `pattern:u` que soluciona tales problemas. Con dicha bandera, una expresión regular maneja correctamente los caracteres de 4 bytes. Y podemos usar la búsqueda de propiedades Unicode, que veremos a continuación. |
33 | 33 |
|
34 | | -## Unicode properties \p{...} |
| 34 | +## Propiedades Unicode \p{...} |
35 | 35 |
|
36 | | -```warn header="Not supported in Firefox and Edge" |
37 | | -Despite being a part of the standard since 2018, unicode properties are not supported in Firefox ([bug](https://bugzilla.mozilla.org/show_bug.cgi?id=1361876)) and Edge ([bug](https://github.com/Microsoft/ChakraCore/issues/2969)). |
| 36 | +```warn header="No es compatible con Firefox y Edge" |
| 37 | +A pesar de ser parte del estándar desde 2018, las propiedades unicode no son compatibles con Firefox ([bug](https://bugzilla.mozilla.org/show_bug.cgi?id=1361876)) y Edge ([bug](https://github.com/Microsoft/ChakraCore/issues/2969)). |
38 | 38 |
|
39 | | -There's [XRegExp](http://xregexp.com) library that provides "extended" regular expressions with cross-browser support for unicode properties. |
| 39 | +La libreria [XRegExp](http://xregexp.com) proporciona expresiones regulares "extendidas" con soporte de propiedades unicode en diferentes navegadores. |
40 | 40 | ``` |
41 | 41 |
|
42 | | -Every character in Unicode has a lot of properties. They describe what "category" the character belongs to, contain miscellaneous information about it. |
| 42 | +Cada carácter en Unicode tiene varias propiedades. Describen a qué "categoría" pertenece el carácter, contienen información diversa al respecto. |
43 | 43 |
|
44 | | -For instance, if a character has `Letter` property, it means that the character belongs to an alphabet (of any language). And `Number` property means that it's a digit: maybe Arabic or Chinese, and so on. |
| 44 | +Por ejemplo, si un carácter tiene la propiedad `Letter`, significa que pertenece a un alfabeto (de cualquier idioma). Y la propiedad `Number` significa que es un dígito: tal vez árabe o chino, y así sucesivamente. |
45 | 45 |
|
46 | | -We can search for characters with a property, written as `pattern:\p{…}`. To use `pattern:\p{…}`, a regular expression must have flag `pattern:u`. |
| 46 | +Podemos buscar caracteres por su propiedad, usando `pattern:\p{...}`. Para usar `pattern:\p{...}`, una expresión regular debe usar también `pattern:u`. |
47 | 47 |
|
48 | | -For instance, `\p{Letter}` denotes a letter in any of language. We can also use `\p{L}`, as `L` is an alias of `Letter`. There are shorter aliases for almost every property. |
| 48 | +Por ejemplo, `\p{Letter}` denota una letra en cualquiera de los idiomas. También podemos usar `\p{L}`, ya que `L` es un alias de `Letter`. Casi todas las propiedades tienen alias cortos. |
49 | 49 |
|
50 | | -In the example below three kinds of letters will be found: English, Georgean and Korean. |
| 50 | +En el ejemplo a continuación se encontrarán tres tipos de letras: inglés, georgiano y coreano. |
51 | 51 |
|
52 | 52 | ```js run |
53 | 53 | let str = "A ბ ㄱ"; |
54 | 54 |
|
55 | 55 | alert( str.match(/\p{L}/gu) ); // A,ბ,ㄱ |
56 | | -alert( str.match(/\p{L}/g) ); // null (no matches, as there's no flag "u") |
| 56 | +alert( str.match(/\p{L}/g) ); // null (sin coincidencia, como no hay bandera "u") |
57 | 57 | ``` |
58 | 58 |
|
59 | | -Here's the main character categories and their subcategories: |
60 | | - |
61 | | -- Letter `L`: |
62 | | - - lowercase `Ll` |
63 | | - - modifier `Lm`, |
64 | | - - titlecase `Lt`, |
65 | | - - uppercase `Lu`, |
66 | | - - other `Lo`. |
67 | | -- Number `N`: |
68 | | - - decimal digit `Nd`, |
69 | | - - letter number `Nl`, |
70 | | - - other `No`. |
71 | | -- Punctuation `P`: |
72 | | - - connector `Pc`, |
73 | | - - dash `Pd`, |
74 | | - - initial quote `Pi`, |
75 | | - - final quote `Pf`, |
76 | | - - open `Ps`, |
77 | | - - close `Pe`, |
78 | | - - other `Po`. |
79 | | -- Mark `M` (accents etc): |
80 | | - - spacing combining `Mc`, |
81 | | - - enclosing `Me`, |
82 | | - - non-spacing `Mn`. |
83 | | -- Symbol `S`: |
84 | | - - currency `Sc`, |
85 | | - - modifier `Sk`, |
86 | | - - math `Sm`, |
87 | | - - other `So`. |
88 | | -- Separator `Z`: |
89 | | - - line `Zl`, |
90 | | - - paragraph `Zp`, |
91 | | - - space `Zs`. |
92 | | -- Other `C`: |
| 59 | +Estas son las principales categorías y subcategorías de caracteres: |
| 60 | + |
| 61 | +- Letter (Letra) `L`: |
| 62 | + - lowercase (minúscula) `Ll` |
| 63 | + - modifier (modificador) `Lm`, |
| 64 | + - titlecase (capitales) `Lt`, |
| 65 | + - uppercase (mayúscula) `Lu`, |
| 66 | + - other (otro) `Lo`. |
| 67 | +- Number (número) `N`: |
| 68 | + - decimal digit (dígito decimal) `Nd`, |
| 69 | + - letter number (número de letras) `Nl`, |
| 70 | + - other (otro) `No`. |
| 71 | +- Punctuation (puntuación) `P`: |
| 72 | + - connector (conector) `Pc`, |
| 73 | + - dash (guión) `Pd`, |
| 74 | + - initial quote (comilla inicial) `Pi`, |
| 75 | + - final quote (comilla final) `Pf`, |
| 76 | + - open (abre) `Ps`, |
| 77 | + - close (cierra) `Pe`, |
| 78 | + - other (otro) `Po`. |
| 79 | +- Mark (marca) `M` (acentos etc): |
| 80 | + - spacing combining (combinación de espacios) `Mc`, |
| 81 | + - enclosing (encerrado) `Me`, |
| 82 | + - non-spacing (sin espaciado) `Mn`. |
| 83 | +- Symbol (símbolo) `S`: |
| 84 | + - currency (moneda) `Sc`, |
| 85 | + - modifier (modificador) `Sk`, |
| 86 | + - math (matemática) `Sm`, |
| 87 | + - other (otro) `So`. |
| 88 | +- Separator (separador) `Z`: |
| 89 | + - line (línea) `Zl`, |
| 90 | + - paragraph (párrafo)`Zp`, |
| 91 | + - space (espacio) `Zs`. |
| 92 | +- Other (otros) `C`: |
93 | 93 | - control `Cc`, |
94 | | - - format `Cf`, |
95 | | - - not assigned `Cn`, |
96 | | - -- private use `Co`, |
97 | | - - surrogate `Cs`. |
| 94 | + - format (formato) `Cf`, |
| 95 | + - not assigned (sin asignación) `Cn`, |
| 96 | + - private use (uso privado) `Co`, |
| 97 | + - surrogate (sustitudo) `Cs`. |
98 | 98 |
|
99 | 99 |
|
100 | | -So, e.g. if we need letters in lower case, we can write `pattern:\p{Ll}`, punctuation signs: `pattern:\p{P}` and so on. |
| 100 | +Entonces, por ejemplo si necesitamos letras en minúsculas, podemos escribir `pattern:\p{Ll}`, signos de puntuación: `pattern:\p{P}` y así sucesivamente. |
101 | 101 |
|
102 | | -There are also other derived categories, like: |
103 | | -- `Alphabetic` (`Alpha`), includes Letters `L`, plus letter numbers `Nl` (e.g. Ⅻ - a character for the roman number 12), plus some other symbols `Other_Alphabetic` (`OAlpha`). |
104 | | -- `Hex_Digit` includes hexadecimal digits: `0-9`, `a-f`. |
105 | | -- ...And so on. |
| 102 | +También hay otras categorías derivadas, como: |
| 103 | +- `Alphabetic` (alfabético) (`Alfa`), incluye letras `L`, más números de letras `Nl` (por ejemplo, Ⅻ - un carácter para el número romano 12), y otros símbolos `Other_Alphabetic` (`OAlpha`). |
| 104 | +- `Hex_Digit` incluye dígitos hexadecimales: `0-9`, `a-f`. |
| 105 | +- ...Y así. |
106 | 106 |
|
107 | | -Unicode supports many different properties, their full list would require a lot of space, so here are the references: |
| 107 | +Unicode admite muchas propiedades diferentes, la lista completa es muy grande, estas son las referencias: |
108 | 108 |
|
109 | | -- List all properties by a character: <https://unicode.org/cldr/utility/character.jsp>. |
110 | | -- List all characters by a property: <https://unicode.org/cldr/utility/list-unicodeset.jsp>. |
111 | | -- Short aliases for properties: <https://www.unicode.org/Public/UCD/latest/ucd/PropertyValueAliases.txt>. |
112 | | -- A full base of Unicode characters in text format, with all properties, is here: <https://www.unicode.org/Public/UCD/latest/ucd/>. |
| 109 | +- Lista de todas las propiedades por carácter: https://unicode.org/cldr/utility/character.jsp (enlace no disponible). |
| 110 | +- Lista de caracteres por propiedad: <https://unicode.org/cldr/utility/list-unicodeset.jsp>. (enlace no disponible) |
| 111 | +- Alias cortos para propiedades: <https://www.unicode.org/Public/UCD/latest/ucd/PropertyValueAliases.txt>. |
| 112 | +- Aquí una base completa de caracteres Unicode en formato de texto, con todas las propiedades: <https://www.unicode.org/Public/UCD/latest/ucd/>. |
113 | 113 |
|
114 | | -### Example: hexadecimal numbers |
| 114 | +### Ejemplo: números hexadecimales |
115 | 115 |
|
116 | | -For instance, let's look for hexadecimal numbers, written as `xFF`, where `F` is a hex digit (0..1 or A..F). |
| 116 | +Por ejemplo, busquemos números hexadecimales, como `xFF`, donde` F` es un dígito hexadecimal (0..1 o A..F). |
117 | 117 |
|
118 | | -A hex digit can be denoted as `pattern:\p{Hex_Digit}`: |
| 118 | +Un dígito hexadecimal se denota como `pattern:\p{Hex_Digit}`: |
119 | 119 |
|
120 | 120 | ```js run |
121 | 121 | let regexp = /x\p{Hex_Digit}\p{Hex_Digit}/u; |
122 | 122 |
|
123 | | -alert("number: xAF".match(regexp)); // xAF |
| 123 | +alert("número: xAF".match(regexp)); // xAF |
124 | 124 | ``` |
125 | 125 |
|
126 | | -### Example: Chinese hieroglyphs |
| 126 | +### Ejemplo: sinogramas chinos |
127 | 127 |
|
128 | | -Let's look for Chinese hieroglyphs. |
| 128 | +Busquemos sinogramas chinos. |
129 | 129 |
|
130 | | -There's a unicode property `Script` (a writing system), that may have a value: `Cyrillic`, `Greek`, `Arabic`, `Han` (Chinese) and so on, [here's the full list]("https://en.wikipedia.org/wiki/Script_(Unicode)"). |
| 130 | +Hay una propiedad Unicode `Script` (un sistema de escritura), que puede tener un valor: `Cyrillic`, `Greek`, `Arabic`, `Han` (chino), etc. [lista completa](https://en.wikipedia.org/wiki/Script_(Unicode)). |
131 | 131 |
|
132 | | -To look for characters in a given writing system we should use `pattern:Script=<value>`, e.g. for Cyrillic letters: `pattern:\p{sc=Cyrillic}`, for Chinese hieroglyphs: `pattern:\p{sc=Han}`, and so on: |
| 132 | +Para buscar caracteres de un sistema de escritura dado, debemos usar `pattern:Script=<value>`, por ejemplo para letras cirílicas: `pattern:\p{sc=Cyrillic}`, para sinogramas chinos: `pattern:\p{sc=Han}`, y así sucesivamente: |
133 | 133 |
|
134 | 134 | ```js run |
135 | | -let regexp = /\p{sc=Han}/gu; // returns Chinese hieroglyphs |
| 135 | +let regexp = /\p{sc=Han}/gu; // devuelve sinogramas chinos |
136 | 136 |
|
137 | 137 | let str = `Hello Привет 你好 123_456`; |
138 | 138 |
|
139 | 139 | alert( str.match(regexp) ); // 你,好 |
140 | 140 | ``` |
141 | 141 |
|
142 | | -### Example: currency |
| 142 | +### Ejemplo: moneda |
143 | 143 |
|
144 | | -Characters that denote a currency, such as `$`, `€`, `¥`, have unicode property `pattern:\p{Currency_Symbol}`, the short alias: `pattern:\p{Sc}`. |
| 144 | +Los caracteres que denotan una moneda, como `$`, `€`, `¥`, tienen la propiedad unicode `pattern:\p{Currency_Symbol}`, el alias corto: `pattern:\p{Sc}`. |
145 | 145 |
|
146 | | -Let's use it to look for prices in the format "currency, followed by a digit": |
| 146 | +Usémoslo para buscar precios en el formato "moneda, seguido de un dígito": |
147 | 147 |
|
148 | 148 | ```js run |
149 | 149 | let regexp = /\p{Sc}\d/gu; |
150 | 150 |
|
151 | | -let str = `Prices: $2, €1, ¥9`; |
| 151 | +let str = `Precios: $2, €1, ¥9`; |
152 | 152 |
|
153 | 153 | alert( str.match(regexp) ); // $2,€1,¥9 |
154 | 154 | ``` |
155 | 155 |
|
156 | | -Later, in the article <info:regexp-quantifiers> we'll see how to look for numbers that contain many digits. |
| 156 | +Más adelante, en el artículo <info:regexp-quantifiers> veremos cómo buscar números que contengan muchos dígitos. |
157 | 157 |
|
158 | | -## Summary |
| 158 | +## Resumen |
159 | 159 |
|
160 | | -Flag `pattern:u` enables the support of Unicode in regular expressions. |
| 160 | +La bandera `pattern:u` habilita el soporte de Unicode en expresiones regulares. |
161 | 161 |
|
162 | | -That means two things: |
| 162 | +Eso significa dos cosas: |
163 | 163 |
|
164 | | -1. Characters of 4 bytes are handled correctly: as a single character, not two 2-byte characters. |
165 | | -2. Unicode properties can be used in the search: `\p{…}`. |
| 164 | +1. Los caracteres de 4 bytes se manejan correctamente: como un solo carácter, no dos caracteres de 2 bytes. |
| 165 | +2. Las propiedades Unicode se pueden usar en las búsquedas: `\p{…}`. |
166 | 166 |
|
167 | | -With Unicode properties we can look for words in given languages, special characters (quotes, currencies) and so on. |
| 167 | +Con las propiedades Unicode podemos buscar palabras en determinados idiomas, caracteres especiales (comillas, monedas), etc. |
0 commit comments