Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

URL objects#376

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Merged
joaquinelio merged 18 commits intojavascript-tutorial:masterfromAgus-c:master
Sep 20, 2020
Merged
Changes fromall commits
Commits
Show all changes
18 commits
Select commitHold shift + click to select a range
898fe57
Update article.md
Agus-cAug 25, 2020
eb15c07
Update article.md
Agus-cAug 25, 2020
73fb0b3
Update article.md
Agus-cAug 31, 2020
f4a447d
Update 5-network/07-url/article.md
Agus-cSep 17, 2020
745b03c
Update 5-network/07-url/article.md
Agus-cSep 17, 2020
646464f
Update 5-network/07-url/article.md
Agus-cSep 17, 2020
b84cccc
Update 5-network/07-url/article.md
Agus-cSep 17, 2020
45fbab4
Update 5-network/07-url/article.md
Agus-cSep 17, 2020
d6c7495
Update 5-network/07-url/article.md
Agus-cSep 17, 2020
78088ea
Update 5-network/07-url/article.md
Agus-cSep 17, 2020
3814ba8
Update 5-network/07-url/article.md
Agus-cSep 17, 2020
f615d7b
Update 5-network/07-url/article.md
Agus-cSep 17, 2020
aa98c6d
Update 5-network/07-url/article.md
Agus-cSep 17, 2020
a760ce6
Update 5-network/07-url/article.md
Agus-cSep 17, 2020
0b59416
Update 5-network/07-url/article.md
Agus-cSep 17, 2020
78f9b37
Update 5-network/07-url/article.md
Agus-cSep 17, 2020
643ecd4
Update 5-network/07-url/article.md
Agus-cSep 17, 2020
c467e08
Update 5-network/07-url/article.md
Agus-cSep 17, 2020
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
148 changes: 74 additions & 74 deletions5-network/07-url/article.md
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,28 @@

#URL objects
#Objetos URL

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');
Expand All@@ -32,7 +32,7 @@ alert(url1); // https://javascript.info/profile/admin
alert(url2); // https://javascript.info/profile/admin
```

We can easily create a newURLbased on the path relative to an existingURL:
Fácilmente podemos crear una nuevaURLbasada en la ruta relativa a unaURL existente:

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

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

```js run
let url = new URL('https://javascript.info/url');
Expand All@@ -51,130 +51,130 @@ alert(url.host); // javascript.info
alert(url.pathname); // /url
```

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

![](url-object.svg)

- `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,
- **`sort()`** --sort parameters byname, rarely needed,
- ...and it's also iterable, similarto `Map`.
- **`append(name, value)`** --añade el parámetro por `name`,
- **`delete(name)`** --elimina el parámetro por `name`,
- **`get(name)`** --obtiene el parámetro por `name`,
- **`getAll(name)`** --obtiene todos los parámetros con el mismo`name` (Eso es posible, por ej. `?user=John&user=Pete`),
- **`has(name)`** --comprueba la existencia del parámetro por`name`,
- **`set(name, value)`** --establece/reemplaza el parámetro,
- **`sort()`** --ordena parámetros por `name`, raramente necesitado,
- ...y además es iterable, similara `Map`.

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

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

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

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

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

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

//iterate over search parameters (decoded)
//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/Тест');

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

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`:

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

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

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

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

Compare it with `encodeURI`:
Compáralo con `encodeURI`:

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

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

````smart header="Encoding difference compared to`URL`"
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:

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

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

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.
````

[8]ページ先頭

©2009-2025 Movatter.jp