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
The built-in[URL](https://url.spec.whatwg.org/#api)class provides a convenient interface for creating and parsing URLs.
4
+
Вбудований клас[URL](https://url.spec.whatwg.org/#api)надає зручний інтерфейс для створення та розбирання URL на частини.
5
5
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
+
Зазвичай, щоб зробити мережевий запит, достатньо передати лише рядок з адресою, передавати саме екземпляр класу `URL`не має жодної потреби. Тому нас ніхто не зобов’язує використовувати клас`URL`. Але іноді це може стати в нагоді.
7
7
8
-
## Creating a URL
8
+
## Створення URL
9
9
10
-
The syntax to create a new `URL`object:
10
+
Синтаксис для створення `URL`об’єктів:
11
11
12
12
```js
13
13
newURL(url, [base])
14
14
```
15
15
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`** -- повний URL чи, якщо задано другий параметр, тільки шлях (дивись далі),
17
+
-**`base`** -- необов’язковий параметр з "основою" відносно якої буде побудовано URL, якщо в першому параметрі передано тільки шлях.
18
18
19
-
For example:
19
+
Наприклад:
20
20
21
21
```js
22
22
let url =newURL('https://javascript.info/profile/admin');
23
23
```
24
24
25
-
These two URLs are same:
25
+
В обох випадках буде згенеровано однакові URL:
26
26
27
27
```js run
28
28
let url1 =newURL('https://javascript.info/profile/admin');
-`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:[email protected]` (not painted above, rarely used).
58
+
-`href`повна URL-адреса, те ж саме, що`url.toString()`
59
+
-`protocol`протокол, закінчується символом двокрапки`:`
60
+
-`search` -- рядок з параметрами, починається символом знаку запитання`?`
61
+
-`hash`починається символом решітки`#`
62
+
-також можуть бути присутні властивості `user`та`password`, якщо використовується формат для HTTP аутентифікації: `http://login:[email protected]` (не згадано вище, бо рідко використовується).
63
63
64
64
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="`URL`об’єкт можна передати у методи, що використовуються для мережевих запитів замість рядку"
66
+
`fetch` чи `XMLHttpRequest` можуть використовувати `URL` об’єкти майже всюди, де можна передати рядок з `URL`.
67
67
68
-
Generally, the `URL`object can be passed to any method instead of a string, as most methods will perform the string conversion, that turns a `URL` object into a string with full URL.
68
+
Зазвичай, `URL`об’єкт можна передати в будь-який метод замість рядку, оскільки більшість методів перетворять об’єкт в рядок, що містить повну URL-адресу.
69
69
```
70
70
71
-
## SearchParams "?..."
71
+
## Параметри пошуку "?..."
72
72
73
-
Let's say we want to create a url with given search params, for instance, `https://google.com/search?query=JavaScript`.
73
+
Припустимо, нам потрібно створити URL-адресу з заданими параметрами пошуку, наприклад, `https://google.com/search?query=JavaScript`.
74
74
75
-
We can provide them in the URL string:
75
+
Ми, звичайно, можемо передати їх в рядку з URL-адресою:
76
76
77
77
```js
78
78
new URL('https://google.com/search?query=JavaScript')
79
79
```
80
80
81
-
...But parameters need to be encoded if they contain spaces, non-latin letters, etc (more about that below).
81
+
...Але параметри повинні бути закодованими, якщо вони містять пробіли, не латинські символи тощо (більше про це нижче).
82
82
83
-
So there's a URL property for that: `url.searchParams`, an object of type[URLSearchParams](https://url.spec.whatwg.org/#urlsearchparams).
83
+
Отже, для цього `URL` має властивість: `url.searchParams`, об’єкт типу[URLSearchParams](https://url.spec.whatwg.org/#urlsearchparams).
84
84
85
-
It provides convenient methods for search parameters:
85
+
Він надає зручні методи для роботи з параметрами пошуку:
86
86
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)`** -- додати параметр з іменем`name`,
88
+
-**`delete(name)`** -- видалити параметр з іменем`name`,
89
+
-**`get(name)`** -- отримати значення параметру з іменем`name`,
90
+
-**`getAll(name)`** -- отримати всі параметри, що мають ім'я`name` (наприклад,`?user=John&user=Pete`),
91
+
-**`has(name)`** -- перевірити чи існує параметр з іменем`name`,
92
+
-**`set(name, value)`** -- встановити/замінити параметр з іменем `name`,
93
+
-**`sort()`** -- відсортувати параметри за іменем, рідко стає в нагоді,
94
+
- ...і це об’єкт також можна перебрати, подібно до`Map`.
95
95
96
-
An example with parameters that contain spaces and punctuation marks:
96
+
Приклад з параметрами, що містять пробіли та знаки пунктуації:
97
97
98
98
```js run
99
99
let url =newURL('https://google.com/search');
100
100
101
-
url.searchParams.set('q', 'test me!'); //added parameter with a space and !
101
+
url.searchParams.set('q', 'test me!'); //додано параметр з пробілом та !
//у циклі перебираємо всі параметри пошуку (кожен параметр автоматично декодується)
111
111
for(let [name, value] ofurl.searchParams) {
112
112
alert(`${name}=${value}`); // q=test me!, then tbs=qdr:y
113
113
}
114
114
```
115
115
116
116
117
-
## Encoding
117
+
## Кодування
118
118
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
+
Набір символів, що можуть дозволено до використання в URL-адресах, визначено в стандарті [RFC3986](https://tools.ietf.org/html/rfc3986).
120
120
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
+
Усі інші символи, що не дозволені стандартом, повинні бути закодовані. Наприклад, не латинські букви та пробіли мають бути замінені на їх UTF-8 коди, що починаються з `%`. Пробіл буде закодовано у вигляді `%20` (з історичних причин пробіл дозволено закодувати як `+`).
122
122
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
+
Гарна новина полягає в тому, що `URL`об’єкт виконає всі перетворення автоматично. Нам потрібно тільки передати всі параметри, а потім перетворити `URL`в рядок:
124
124
125
125
```js run
126
-
//using some cyrillic characters for this example
126
+
//для прикладу використано кириличні символи
127
127
128
-
let url =newURL('https://ru.wikipedia.org/wiki/Тест');
128
+
let url =newURL('https://uk.wikipedia.org/wiki/Тест');
As you can see, both`Тест`in the url path and `ъ` in the parameter are encoded.
134
+
Як бачите, і`Тест`у шляху, і параметр `ї` закодовано.
135
135
136
-
The URL became longer, because each cyrillic letter is represented with two bytes in UTF-8, so there are two `%..` entities.
136
+
URL-адреса стала довшою, бо кожен кириличний символ представлено двома байтами в UTF-8, тому там дві групи символів `%..`.
137
137
138
-
### Encoding strings
138
+
### Кодування рядків
139
139
140
-
In old times, before `URL`objects appeared, people used strings for URLs.
140
+
До появи `URL`об’єктів, розробники використовували рядки для URL-адрес.
141
141
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
+
Наразі, зручніше використовувати`URL`об’єкти, але рядки все ще можна використовувати. У більшості випадків, використання рядків потребує менше коду.
143
143
144
-
If we use a string though, we need to encode/decode special characters manually.
144
+
Слід зауважити, якщо ми використовуємо рядки, то закодувати та декодувати символи нам потрібно вручну.
145
145
146
-
There are built-in functions for that:
146
+
Для цього є вбудовані функції:
147
147
148
-
-[encodeURI](mdn:/JavaScript/Reference/Global_Objects/encodeURI) - encodes URL as a whole.
149
-
-[decodeURI](mdn:/JavaScript/Reference/Global_Objects/decodeURI) - decodes it back.
150
-
-[encodeURIComponent](mdn:/JavaScript/Reference/Global_Objects/encodeURIComponent) - encodes a URL component, such as a search parameter, or a hash, or a pathname.
151
-
-[decodeURIComponent](mdn:/JavaScript/Reference/Global_Objects/decodeURIComponent) - decodes it back.
-[encodeURIComponent](mdn:/JavaScript/Reference/Global_Objects/encodeURIComponent) - закодувати частину URL-адреси, наприклад, параметри пошуку, шлях чи хеш.
A natural question is: "What's the difference between `encodeURIComponent`and`encodeURI`? When we should use either?"
153
+
Може виникнути природне питання: "Яка різниця між `encodeURIComponent`та`encodeURI`? Коли використовувати яку?"
154
154
155
-
That's easy to understand if we look at the URL, that's split into components in the picture above:
155
+
Це легше зрозуміти, якщо подивитися на URL-адресу, що показано розділеною на частини вище.
156
156
157
157
```
158
158
https://site.com:8080/path/page?p1=v1&p2=v2#hash
159
159
```
160
160
161
-
As we can see, characters such as `:`, `?`, `=`, `&`, `#`are allowed in URL.
161
+
Як бачимо, символи `:`, `?`, `=`, `&`, `#`дозволено безпосередньо використовувати в URL.
162
162
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
+
...На противагу цьому, якщо ми поглянемо тільки на параметри пошуку URL, то використані там символи повинні бути закодовані, щоб не зламати форматування.
164
164
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`кодує тільки символи, що заборонені до використання в URL.
166
+
-`encodeURIComponent`закодує деякі символи та символи: `#`, `$`, `&`, `+`, `,`, `/`, `:`, `;`, `=`, `?`та`@`.
167
167
168
-
So, for a whole URL we can use`encodeURI`:
168
+
Отже, для кодування всього URL можна використати`encodeURI`:
As we can see, `encodeURI`does not encode`&`, as this is a legit character in URL as a whole.
195
+
Як бачимо, `encodeURI`не кодує символ`&`, оскільки це дозволений для використання в URL.
196
196
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
+
Але нам потрібно закодувати`&`всередині параметрів пошуку, інакше ми отримаємо`q=Rock&Roll`, що означатиме `q=Rock`та незрозумілий параметр `Roll`. Не те, що ми очікували.
198
198
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
+
Нам слід використовувати тільки `encodeURIComponent`з параметрами пошуку для правильного вставлення в рядок URL. Для повної безпеки, слід кодувати ім’я та значення параметрів, якщо ми не можемо бути повністю впевненими, що вони містять тільки дозволені символи.
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="Різниця в кодуванні у порівнянні з`URL`"
202
+
Класи[URL](https://url.spec.whatwg.org/#url-class)та[URLSearchParams](https://url.spec.whatwg.org/#interface-urlsearchparams)ґрунтуються на останній специфікації URL: [RFC3986](https://tools.ietf.org/html/rfc3986), але функції `encode*`використовують застарілу версію[RFC2396](https://www.ietf.org/rfc/rfc2396.txt).
203
203
204
-
There are a few differences, e.g. IPv6 addresses are encoded differently:
204
+
Існують деякі відмінності, як от IPv6 адреси кодуються по-іншому:
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
+
Як бачимо, `encodeURI`замінила квадратні дужки`[...]`, що є помилкою, причиною є те, що IPv6 адреси ще не існували в часи створення стандарту RFC2396 (серпень 1998).
215
215
216
-
Such cases are rare, `encode*`functions work well most of the time.
216
+
Такі випадки рідко трапляються, функції `encode*`добре справляються в більшості випадків.
0 commit comments