Skip to content

Commit 304689c

Browse files
authored
Merge pull request #376 from Agus-c/master
URL objects
2 parents 0f685c6 + c467e08 commit 304689c

File tree

1 file changed

+74
-74
lines changed

1 file changed

+74
-74
lines changed

5-network/07-url/article.md

Lines changed: 74 additions & 74 deletions
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,28 @@
11

2-
# URL objects
2+
# Objetos URL
33

4-
The built-in [URL](https://url.spec.whatwg.org/#api) class provides a convenient interface for creating and parsing URLs.
4+
La clase [URL](https://url.spec.whatwg.org/#api) incorporada brinda una interfaz conveniente para crear y analizar URLs.
55

6-
There are no networking methods that require exactly a `URL` object, strings are good enough. So technically we don't have to use `URL`. But sometimes it can be really helpful.
6+
No hay métodos de networking que requieran exactamente un objeto `URL`, los strings son suficientemente buenos para eso. Así que técnicamente no tenemos que usar `URL`. Pero a veces puede ser realmente útil.
77

8-
## Creating a URL
8+
## Creando una URL
99

10-
The syntax to create a new `URL` object:
10+
La sintaxis para crear un nuevo objeto `URL` es:
1111

1212
```js
1313
new URL(url, [base])
1414
```
1515

16-
- **`url`** -- the full URL or only path (if base is set, see below),
17-
- **`base`** -- an optional base URL: if set and `url` argument has only path, then the URL is generated relative to `base`.
16+
- **`url`** -- La URL completa o ruta única (si se establece base, mira a continuación),
17+
- **`base`** - una URL base opcional: si se establece y el argumento `url` solo tiene una ruta, entonces la URL se genera relativa a `base`.
1818

19-
For example:
19+
Por ejemplo:
2020

2121
```js
2222
let url = new URL('https://javascript.info/profile/admin');
2323
```
2424

25-
These two URLs are same:
25+
Estas dos URLs son las mismas:
2626

2727
```js run
2828
let url1 = new URL('https://javascript.info/profile/admin');
@@ -32,7 +32,7 @@ alert(url1); // https://javascript.info/profile/admin
3232
alert(url2); // https://javascript.info/profile/admin
3333
```
3434

35-
We can easily create a new URL based on the path relative to an existing URL:
35+
Fácilmente podemos crear una nueva URL basada en la ruta relativa a una URL existente:
3636

3737
```js run
3838
let url = new URL('https://javascript.info/profile/admin');
@@ -41,7 +41,7 @@ let newUrl = new URL('tester', url);
4141
alert(newUrl); // https://javascript.info/profile/tester
4242
```
4343

44-
The `URL` object immediately allows us to access its components, so it's a nice way to parse the url, e.g.:
44+
El objeto `URL` inmediatamente nos permite acceder a sus componentes, por lo que es una buena manera de analizar la url, por ej.:
4545

4646
```js run
4747
let url = new URL('https://javascript.info/url');
@@ -51,130 +51,130 @@ alert(url.host); // javascript.info
5151
alert(url.pathname); // /url
5252
```
5353

54-
Here's the cheatsheet for URL components:
54+
Aquí está la hoja de trucos para los componentes URL:
5555

5656
![](url-object.svg)
5757

58-
- `href` is the full url, same as `url.toString()`
59-
- `protocol` ends with the colon character `:`
60-
- `search` - a string of parameters, starts with the question mark `?`
61-
- `hash` starts with the hash character `#`
62-
- there may be also `user` and `password` properties if HTTP authentication is present: `http://login:password@site.com` (not painted above, rarely used).
58+
- `href` es la url completa, igual que `url.toString()`
59+
- `protocol` acaba con el carácter dos puntos `:`
60+
- `search` - un string de parámetros, comienza con el signo de interrogación `?`
61+
- `hash` comienza con el carácter de hash `#`
62+
- También puede haber propiedades `user` y `password` si la autenticación HTTP esta presente: `http://login:password@site.com` (no mostrados arriba, raramente usados)
6363

6464

65-
```smart header="We can pass `URL` objects to networking (and most other) methods instead of a string"
66-
We can use a `URL` object in `fetch` or `XMLHttpRequest`, almost everywhere where a URL-string is expected.
65+
```smart header="Podemos pasar objetos `URL` a métodos de red (y la mayoría de los demás) en lugar de un string"
66+
Podemos usar un objeto `URL` en `fetch` o `XMLHttpRequest`, casi en todas partes donde se espera un URL-string.
6767

68-
Generally, `URL` object can be passed to any method instead of a string, as most method will perform the string conversion, that turns a `URL` object into a string with full URL.
68+
Generalmente, un objeto `URL` puede pasarse a cualquier método en lugar de un string, ya que la mayoría de métodos llevarán a cabo la conversión del string, eso convierte un objeto `URL` en un string con URL completa.
6969
```
7070
71-
## SearchParams "?..."
71+
## Parámetros de búsqueda "?..."
7272
73-
Let's say we want to create a url with given search params, for instance, `https://google.com/search?query=JavaScript`.
73+
Digamos que queremos crear una url con determinados parámetros de búsqueda, por ejemplo, `https://google.com/search?query=JavaScript`.
7474
75-
We can provide them in the URL string:
75+
Podemos proporcionarlos en el string URL:
7676
7777
```js
7878
new URL('https://google.com/search?query=JavaScript')
7979
```
8080

81-
...But parameters need to be encoded if they contain spaces, non-latin letters, etc (more about that below).
81+
...Pero los parámetros necesitan estar codificados si contienen espacios, letras no latinas, entre otros (Más sobre eso debajo).
8282

83-
So there's URL property for that: `url.searchParams`, an object of type [URLSearchParams](https://url.spec.whatwg.org/#urlsearchparams).
83+
Por lo que existe una propiedad URL para eso: `url.searchParams`, un objeto de tipo [URLSearchParams](https://url.spec.whatwg.org/#urlsearchparams).
8484

85-
It provides convenient methods for search parameters:
85+
Esta proporciona métodos convenientes para los parámetros de búsqueda:
8686

87-
- **`append(name, value)`** -- add the parameter by `name`,
88-
- **`delete(name)`** -- remove the parameter by `name`,
89-
- **`get(name)`** -- get the parameter by `name`,
90-
- **`getAll(name)`** -- get all parameters with the same `name` (that's possible, e.g. `?user=John&user=Pete`),
91-
- **`has(name)`** -- check for the existence of the parameter by `name`,
92-
- **`set(name, value)`** -- set/replace the parameter,
93-
- **`sort()`** -- sort parameters by name, rarely needed,
94-
- ...and it's also iterable, similar to `Map`.
87+
- **`append(name, value)`** -- añade el parámetro por `name`,
88+
- **`delete(name)`** -- elimina el parámetro por `name`,
89+
- **`get(name)`** -- obtiene el parámetro por `name`,
90+
- **`getAll(name)`** -- obtiene todos los parámetros con el mismo `name` (Eso es posible, por ej. `?user=John&user=Pete`),
91+
- **`has(name)`** -- comprueba la existencia del parámetro por `name`,
92+
- **`set(name, value)`** -- establece/reemplaza el parámetro,
93+
- **`sort()`** -- ordena parámetros por `name`, raramente necesitado,
94+
- ...y además es iterable, similar a `Map`.
9595

96-
An example with parameters that contain spaces and punctuation marks:
96+
Un ejemplo con parámetros que contienen espacios y signos de puntuación:
9797

9898
```js run
9999
let url = new URL('https://google.com/search');
100100

101-
url.searchParams.set('q', 'test me!'); // added parameter with a space and !
101+
url.searchParams.set('q', 'test me!'); // Parámetro añadido con un espacio y !
102102

103103
alert(url); // https://google.com/search?q=test+me%21
104104

105-
url.searchParams.set('tbs', 'qdr:y'); // added parameter with a colon :
105+
url.searchParams.set('tbs', 'qdr:y'); // Parámetro añadido con dos puntos :
106106

107-
// parameters are automatically encoded
107+
// Los parámetros son automáticamente codificados
108108
alert(url); // https://google.com/search?q=test+me%21&tbs=qdr%3Ay
109109

110-
// iterate over search parameters (decoded)
110+
// Iterar sobre los parametros de búsqueda (Decodificados)
111111
for(let [name, value] of url.searchParams) {
112112
alert(`${name}=${value}`); // q=test me!, then tbs=qdr:y
113113
}
114114
```
115115

116116

117-
## Encoding
117+
## Codificación
118118

119-
There's a standard [RFC3986](https://tools.ietf.org/html/rfc3986) that defines which characters are allowed in URLs and which are not.
119+
Existe un estándar [RFC3986](https://tools.ietf.org/html/rfc3986) que define cuales caracteres son permitidos en URLs y cuales no.
120120

121-
Those that are not allowed, must be encoded, for instance non-latin letters and spaces - replaced with their UTF-8 codes, prefixed by `%`, such as `%20` (a space can be encoded by `+`, for historical reasons, but that's an exception).
121+
Esos que no son permitidos, deben ser codificados, por ejemplo letras no latinas y espacios - reemplazados con sus códigos UTF-8, con el prefijo `%`, tal como `%20` (un espacio puede ser codificado con `+`, por razones históricas, pero esa es una excepción).
122122

123-
The good news is that `URL` objects handle all that automatically. We just supply all parameters unencoded, and then convert the `URL` to string:
123+
La buena noticia es que los objetos `URL` manejan todo eso automáticamente. Nosotros sólo proporcionamos todos los parámetros sin codificar, y luego convertimos la `URL` a string:
124124

125125
```js run
126-
// using some cyrillic characters for this example
126+
// Usando algunos caracteres cirílicos para este ejemplo
127127

128128
let url = new URL('https://ru.wikipedia.org/wiki/Тест');
129129

130130
url.searchParams.set('key', 'ъ');
131131
alert(url); //https://ru.wikipedia.org/wiki/%D0%A2%D0%B5%D1%81%D1%82?key=%D1%8A
132132
```
133133

134-
As you can see, both `Тест` in the url path and `ъ` in the parameter are encoded.
134+
Como puedes ver, ambos `Тест` en la ruta url y `ъ` en el parámetro están codificados.
135135

136-
The URL became longer, because each cyrillic letter is represented with two bytes in UTF-8, so there are two `%..` entities.
136+
La URL se alarga, ya que cada letra cirílica es representada con dos bytes en UTF-8, por lo que hay dos entidades `%..`.
137137

138-
### Encoding strings
138+
### Codificando strings
139139

140-
In old times, before `URL` objects appeared, people used strings for URLs.
140+
En los viejos tiempos, antes de que los objetos `URL` aparecieran, la gente usaba strings para las URL.
141141

142-
As of now, `URL` objects are often more convenient, but strings can still be used as well. In many cases using a string makes the code shorter.
142+
A partir de ahora, los objetos `URL` son frecuentemente más convenientes, pero también aún pueden usarse los strings. En muchos casos usando un string se acorta el código.
143143

144-
If we use a string though, we need to encode/decode special characters manually.
144+
Aunque si usamos un string, necesitamos codificar/decodificar caracteres especiales manualmente.
145145

146-
There are built-in functions for that:
146+
Existen funciones incorporadas para eso:
147147

148-
- [encodeURI](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURI) - encodes URL as a whole.
149-
- [decodeURI](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/decodeURI) - decodes it back.
150-
- [encodeURIComponent](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent) - encodes a URL component, such as a search parameter, or a hash, or a pathname.
151-
- [decodeURIComponent](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/decodeURIComponent) - decodes it back.
148+
- [encodeURI](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURI) - Codifica la URL como un todo.
149+
- [decodeURI](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/decodeURI) - La decodifica de vuelta.
150+
- [encodeURIComponent](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent) - Codifica un componente URL, como un parametro de busqueda, un hash, o un pathname.
151+
- [decodeURIComponent](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/decodeURIComponent) - La decodifica de vuelta.
152152

153-
A natural question is: "What's the difference between `encodeURIComponent` and `encodeURI`? When we should use either?"
153+
Una pregunta natural es: "¿Cuál es la diferencia entre `encodeURIComponent` y `encodeURI`?¿Cuándo deberíamos usar una u otra?
154154

155-
That's easy to understand if we look at the URL, that's split into components in the picture above:
155+
Eso es fácil de entender si miramos a la URL, que está separada en componentes en la imagen de arriba:
156156

157157
```
158158
https://site.com:8080/path/page?p1=v1&p2=v2#hash
159159
```
160160

161-
As we can see, characters such as `:`, `?`, `=`, `&`, `#` are allowed in URL.
161+
Como podemos ver, caracteres tales como `:`, `?`, `=`, `&`, `#` son admitidos en URL.
162162

163-
...On the other hand, if we look at a single URL component, such as a search parameter, these characters must be encoded, not to break the formatting.
163+
...Por otra parte, si miramos a un único componente URL, como un parámetro de búsqueda, estos caracteres deben estar codificados, para no romper el formateo.
164164

165-
- `encodeURI` encodes only characters that are totally forbidden in URL.
166-
- `encodeURIComponent` encodes same characters, and, in addition to them, characters `#`, `$`, `&`, `+`, `,`, `/`, `:`, `;`, `=`, `?` and `@`.
165+
- `encodeURI` Codifica solo caracteres que están totalmente prohibidos en URL
166+
- `encodeURIComponent` Codifica los mismos caracteres, y, en adición a ellos, los caracteres `#`, `$`, `&`, `+`, `,`, `/`, `:`, `;`, `=`, `?` y `@`.
167167

168-
So, for a whole URL we can use `encodeURI`:
168+
Entonces, para una URL completa podemos usar `encodeURI`:
169169

170170
```js run
171-
// using cyrillic characters in url path
171+
// Usando caracteres cirílicos en el path URL
172172
let url = encodeURI('http://site.com/привет');
173173

174174
alert(url); // http://site.com/%D0%BF%D1%80%D0%B8%D0%B2%D0%B5%D1%82
175175
```
176176

177-
...While for URL parameters we should use `encodeURIComponent` instead:
177+
...Mientras que para parámetros URL deberíamos usar `encodeURIComponent` en su lugar:
178178

179179
```js run
180180
let music = encodeURIComponent('Rock&Roll');
@@ -183,7 +183,7 @@ let url = `https://google.com/search?q=${music}`;
183183
alert(url); // https://google.com/search?q=Rock%26Roll
184184
```
185185

186-
Compare it with `encodeURI`:
186+
Compáralo con `encodeURI`:
187187

188188
```js run
189189
let music = encodeURI('Rock&Roll');
@@ -192,26 +192,26 @@ let url = `https://google.com/search?q=${music}`;
192192
alert(url); // https://google.com/search?q=Rock&Roll
193193
```
194194

195-
As we can see, `encodeURI` does not encode `&`, as this is a legit character in URL as a whole.
195+
Como podemos ver, `encodeURI` no codifica `&`, ya que este es un carácter legítimo en la URL como un todo.
196196

197-
But we should encode `&` inside a search parameter, otherwise, we get `q=Rock&Roll` - that is actually `q=Rock` plus some obscure parameter `Roll`. Not as intended.
197+
Pero debemos codificar `&` dentro de un parámetro de búsqueda, de otra manera, obtendremos `q=Rock&Roll`- que es realmente `q=Rock` más algún parámetro `Roll` oscuro. No según lo previsto.
198198

199-
So we should use only `encodeURIComponent` for each search parameter, to correctly insert it in the URL string. The safest is to encode both name and value, unless we're absolutely sure that it has only allowed characters.
199+
Así que debemos usar solo `encodeURIComponent`para cada parámetro de búsqueda, para insertarlo correctamente en el string URL. Lo más seguro es codificar tanto nombre como valor, a menos que estemos absolutamente seguros de que solo haya admitido caracteres
200200

201-
````smart header="Encoding difference compared to `URL`"
202-
Classes [URL](https://url.spec.whatwg.org/#url-class) and [URLSearchParams](https://url.spec.whatwg.org/#interface-urlsearchparams) are based on the latest URI specification: [RFC3986](https://tools.ietf.org/html/rfc3986), while `encode*` functions are based on the obsolete version [RFC2396](https://www.ietf.org/rfc/rfc2396.txt).
201+
````smart header="Diferencia de codificación comparado con `URL`"
202+
Las clases [URL](https://url.spec.whatwg.org/#url-class) y [URLSearchParams](https://url.spec.whatwg.org/#interface-urlsearchparams) están basadas en la especificación URI mas reciente: [RFC3986](https://tools.ietf.org/html/rfc3986), mientras que las funciones `encode*` están basadas en la versión obsoleta [RFC2396](https://www.ietf.org/rfc/rfc2396.txt).
203203

204-
There are few differences, e.g. IPv6 addresses are encoded differently:
204+
Existen algunas diferencias, por ej. las direcciones IPv6 se codifican de otra forma:
205205

206206
```js run
207-
// valid url with IPv6 address
207+
// Url válida con dirección IPv6
208208
let url = 'http://[2607:f8b0:4005:802::1007]/';
209209

210210
alert(encodeURI(url)); // http://%5B2607:f8b0:4005:802::1007%5D/
211211
alert(new URL(url)); // http://[2607:f8b0:4005:802::1007]/
212212
```
213213

214-
As we can see, `encodeURI` replaced square brackets `[...]`, that's not correct, the reason is: IPv6 urls did not exist at the time of RFC2396 (August 1998).
214+
Como podemos ver, `encodeURI` reemplazó los corchetes `[...]`, eso es incorrecto, la razón es: las urls IPv6 no existían en el tiempo de RFC2396 (August 1998).
215215

216-
Such cases are rare, `encode*` functions work well most of the time.
216+
Tales casos son raros, las funciones `encode*` mayormente funcionan bien.
217217
````

0 commit comments

Comments
 (0)