You signed in with another tab or window.Reload to refresh your session.You signed out in another tab or window.Reload to refresh your session.You switched accounts on another tab or window.Reload to refresh your session.Dismiss alert
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
The built-in [URL](https://url.spec.whatwg.org/#api)class provides a convenient interface for creating and parsing URLs.
La clase [URL](https://url.spec.whatwg.org/#api)incorporada brinda una interfaz conveniente para crear y analizar URLs.
There are nonetworkingmethods that require exactly a `URL` object,stringsare good enough. So technically we don't have to use `URL`.But sometimes it can be really helpful.
No hay métodos denetworkingque requieran exactamente un objeto `URL`, losstringsson suficientemente buenos para eso. Así que técnicamente no tenemos que usar `URL`.Pero a veces puede ser realmente útil.
##Creating a URL
##Creando una URL
The syntax to create a new`URL`object:
La sintaxis para crear un nuevo objeto`URL`es:
```js
new URL(url, [base])
```
- **`url`** --the fullURLor only path (if base is set, see below),
- **`base`** -- an optional baseURL: if set and`url`argument has only path, then the URLis generated relative to `base`.
- **`url`** --LaURLcompleta o ruta única (si se establece base, mira a continuación),
- **`base`** - una URL baseopcional: si se establece y el argumento`url`solo tiene una ruta, entonces la URLse genera relativa a `base`.
For example:
Por ejemplo:
```js
let url = new URL('https://javascript.info/profile/admin');
```
These two URLsare same:
Estas dos URLsson las mismas:
```js run
let url1 = new URL('https://javascript.info/profile/admin');
Aquí está la hoja de trucos para los componentes URL:

- `href`is the fullurl, same as `url.toString()`
- `protocol`ends with the colon character`:`
- `search` -a stringof parameters, starts with the question mark`?`
- `hash`starts with the hash character`#`
-there may be also `user`and `password`properties ifHTTPauthentication is present: `http://login:password@site.com` (not painted above, rarely used).
- `href`es laurl completa, igual que `url.toString()`
- `protocol`acaba con el carácter dos puntos`:`
- `search` -un stringde parámetros, comienza con el signo de interrogación`?`
- `hash`comienza con el carácter de hash`#`
-También puede haber propiedades `user`y `password`si la autenticaciónHTTPesta presente: `http://login:password@site.com` (no mostrados arriba, raramente usados)
```smart header="We can pass `URL`objects to networking (and most other) methods instead of a string"
We can use a `URL`object in`fetch`or `XMLHttpRequest`,almost everywhere where aURL-string is expected.
```smart header="Podemos pasar objetos `URL`a métodos de red (y la mayoría de los demás) en lugar de un string"
Podemos usar un objeto `URL`en`fetch`o `XMLHttpRequest`,casi en todas partes donde se espera unURL-string.
Generally,`URL`object can be passed to any method instead of astring,as most method will perform the string conversion, that turns a`URL`object into astringwith fullURL.
Generalmente, un objeto`URL`puede pasarse a cualquier método en lugar de unstring,ya que la mayoría de métodos llevarán a cabo la conversión del string, eso convierte un objeto`URL`en unstringconURL completa.
```
##SearchParams "?..."
##Parámetros de búsqueda "?..."
Let's say we want to create aurlwith given search params, for instance, `https://google.com/search?query=JavaScript`.
Digamos que queremos crear unaurlcon determinados parámetros de búsqueda, por ejemplo, `https://google.com/search?query=JavaScript`.
We can provide them in theURL string:
Podemos proporcionarlos en el stringURL:
```js
new URL('https://google.com/search?query=JavaScript')
```
...But parameters need to be encoded if they contain spaces, non-latin letters, etc (more about that below).
...Pero los parámetros necesitan estar codificados si contienen espacios, letras no latinas, entre otros (Más sobre eso debajo).
So there's URL property for that: `url.searchParams`,an object of type [URLSearchParams](https://url.spec.whatwg.org/#urlsearchparams).
Por lo que existe una propiedad URL para eso: `url.searchParams`,un objeto de tipo [URLSearchParams](https://url.spec.whatwg.org/#urlsearchparams).
It provides convenient methods for search parameters:
Esta proporciona métodos convenientes para los parámetros de búsqueda:
- **`append(name, value)`** --add the parameter by `name`,
- **`delete(name)`** --remove the parameter by `name`,
- **`get(name)`** --get the parameter by `name`,
- **`getAll(name)`** --get all parameters with the same`name` (that's possible, e.g. `?user=John&user=Pete`),
- **`has(name)`** --check for the existence of the parameter by`name`,
- **`set(name, value)`** --set/replace the parameter,
//Iterar sobre los parametros de búsqueda (Decodificados)
for(let [name, value] of url.searchParams) {
alert(`${name}=${value}`); // q=test me!, then tbs=qdr:y
}
```
##Encoding
##Codificación
There's a standard [RFC3986](https://tools.ietf.org/html/rfc3986)that defines which characters are allowed in URLsand which are not.
Existe un estándar [RFC3986](https://tools.ietf.org/html/rfc3986)que define cuales caracteres son permitidos en URLsy cuales no.
Those that are not allowed, must be encoded, for instance non-latin letters and spaces - replaced with theirUTF-8 codes, prefixed by`%`,such as `%20` (a space can be encoded by `+`,for historical reasons, but that's an exception).
Esos que no son permitidos, deben ser codificados, por ejemplo letras no latinas y espacios - reemplazados con sus códigosUTF-8, con el prefijo`%`,tal como `%20` (un espacio puede ser codificado con `+`,por razones históricas, pero esa es una excepción).
The good news is that`URL`objects handle all that automatically. We just supply all parameters unencoded, and then convert the `URL`to string:
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:
```js run
//using some cyrillic characters for this example
//Usando algunos caracteres cirílicos para este ejemplo
let url = new URL('https://ru.wikipedia.org/wiki/Тест');
As you can see, both `Тест`in theurlpath and`ъ`in the parameter are encoded.
Como puedes ver, ambos `Тест`en la rutaurly`ъ`en el parámetro están codificados.
The URLbecame longer, because each cyrillic letter is represented with twobytesin UTF-8,so there are two`%..` entities.
La URLse alarga, ya que cada letra cirílica es representada con dosbytesen UTF-8,por lo que hay dos entidades`%..`.
###Encoding strings
###Codificando strings
In old times, before`URL`objects appeared, people usedstringsfor URLs.
En los viejos tiempos, antes de que los objetos`URL`aparecieran, la gente usabastringspara las URL.
As of now,`URL`objects are often more convenient, but strings can still be used as well. In many cases using a stringmakes the code shorter.
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 stringse acorta el código.
If we use a string though, we need to encode/decode special characters manually.
Aunque si usamos un string, necesitamos codificar/decodificar caracteres especiales manualmente.
There are built-in functions for that:
Existen funciones incorporadas para eso:
- [encodeURI](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURI) -encodesURLas a whole.
- [decodeURI](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/decodeURI) -decodes it back.
- [encodeURIComponent](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent) -encodes a URL component, such as a search parameter, or ahash,or a pathname.
- [decodeURIComponent](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/decodeURIComponent) -decodes it back.
- [encodeURI](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURI) -Codifica laURLcomo un todo.
- [decodeURI](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/decodeURI) -La decodifica de vuelta.
- [encodeURIComponent](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent) -Codifica un componente URL, como un parametro de busqueda, unhash,o un pathname.
- [decodeURIComponent](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/decodeURIComponent) -La decodifica de vuelta.
Anaturalquestion is: "What's the difference between`encodeURIComponent`and `encodeURI`? When we should use either?"
Una preguntanaturales: "¿Cuál es la diferencia entre`encodeURIComponent`y `encodeURI`?¿Cuándo deberíamos usar una u otra?
That's easy to understand if we look at the URL,that's split into components in the picture above:
Eso es fácil de entender si miramos a la URL,que está separada en componentes en la imagen de arriba:
```
https://site.com:8080/path/page?p1=v1&p2=v2#hash
```
As we can see, characters such as `:`, `?`, `=`, `&`, `#`are allowed in URL.
Como podemos ver, caracteres tales como `:`, `?`, `=`, `&`, `#`son admitidos en URL.
...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.
...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.
- `encodeURI`encodes only characters that are totally forbidden in URL.
- `encodeURIComponent`encodes same characters, and, in addition to them, characters`#`, `$`, `&`, `+`, `,`, `/`, `:`, `;`, `=`, `?`and `@`.
- `encodeURI`Codifica solo caracteres que están totalmente prohibidos en URL
- `encodeURIComponent`Codifica los mismos caracteres, y, en adición a ellos, los caracteres`#`, `$`, `&`, `+`, `,`, `/`, `:`, `;`, `=`, `?`y `@`.
So, for a wholeURLwe can use `encodeURI`:
Entonces, para unaURLcompleta podemos usar `encodeURI`:
As we can see, `encodeURI`does not encode`&`,as this is a legit character inURLas a whole.
Como podemos ver, `encodeURI`no codifica`&`,ya que este es un carácter legítimo en laURLcomo un todo.
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.
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.
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.
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
Classes[URL](https://url.spec.whatwg.org/#url-class)and [URLSearchParams](https://url.spec.whatwg.org/#interface-urlsearchparams)are based on the latest URIspecification: [RFC3986](https://tools.ietf.org/html/rfc3986),while`encode*`functions are based on the obsolete version [RFC2396](https://www.ietf.org/rfc/rfc2396.txt).
````smart header="Diferencia de codificación comparado con`URL`"
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 URImas 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).
There are few differences, e.g.IPv6addresses are encoded differently:
Existen algunas diferencias, por ej. las direccionesIPv6se codifican de otra forma:
As we can see, `encodeURI`replaced square brackets `[...]`,that's not correct, the reason is: IPv6 urlsdid not exist at the time of RFC2396 (August 1998).
Como podemos ver, `encodeURI`reemplazó los corchetes `[...]`,eso es incorrecto, la razón es: las urlsIPv6 no existían en el tiempo de RFC2396 (August 1998).
Such cases are rare,`encode*`functions work well most of the time.
Tales casos son raros, las funciones`encode*`mayormente funcionan bien.
````
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.