URL Objects
JavaScript URL Objects (JavaScript URL对象)
This chapter examines URL objects in JavaScript. The JavaScript built-in URL class provides a flexible interface that allows both to create and parse URLs . (本章研究JavaScript中的URL对象。 JavaScript内置URL类提供了一个灵活的接口,允许创建和解析URL。)
No networking methods requiring a URL object exist now. Strings are rather convenient for that. So, technically, you needn’t always use URLs, but in some instances, they are handy. Let’s dive into some details. (现在不存在需要URL对象的网络方法。弦对此相当方便。因此,从技术上讲,您不必总是使用URL ,但在某些情况下,它们很方便。让我们深入了解一些细节。)
How to Generate a URLThe basic syntax used for generating a URL is the following:
How to Generate a URLThe basic syntax used for generating a URL is the following:
The basic syntax used for generating a URL is the following:
new URL(url, [base])
Here is how an example of a URL looks like:
let url = new URL('https://w3cdoc/admin');
Now, let’s check out two URLs that are equivalent:
let url1 = new URL('https://w3cdoc.com/admin');
let url2 = new URL('/admin', 'https://w3cdoc.com');
console.log(url1); // https://w3cdoc.com/admin
console.log(url2); // https://w3cdoc.com/admin
A new URL can be generated on the basis of the existing ones:
let url = new URL('https://w3cdoc.com/tester');
let newUrl = new URL('tester', url);
console.log(newUrl); // https://w3cdoc.com/tester
It is possible to access the URL components at once. Hence, it allows parsing the URL like this:
let url = new URL('https://w3cdoc.com/url');
console.log(url.protocol); // https:
console.log(url.host); // w3cdoc
console.log(url.pathname); // /url
Please, take into consideration another essential thing: passing URL objects to networking methods can be used instead of a string. A URL object may be applied in fetch or XMLHttpRequest almost anywhere a URL -string is scheduled.
About The Search Params
About The Search Params (关于搜索参数)
Often it’s necessary to generate a URL with specific search params (for instance,https://google.com/search?query=JavaScript. They may be supplied inside a URL string like here:
new URL('https://google.com/search?query=JavaScript')
But, in case the parameters include spaces, it is required to encode them. A URL property such as url.searchParams is used to meet that aim. An example of parameters containing punctuation marks and spaces is shown below:
let url = new URL('https://w3cdoc.com/search');
url.searchParams.set('s', 'find book!'); //added parameter with space and!
console.log(url); // https://google.com/search?s=find+book%21
url.searchParams.set('tbs', 'qdr:x'); // colon option added:
// parameters are automatically encoded
console.log(url); // https://w3cdoc.com/search?s=find+book%21&tbs=qdr%3Ax
// iterate over the search parameters (decoded)
for (let [name, value] of url.searchParams) {
console.log(`${name}=${value}`); // s=find book!, then tbs=qdr:x
}
About the Encoding of URLs
About the Encoding of URLs (关于URL的编码)
When certain characters are not allowed in URLs, they should be encoded. That process is automatically handled by URL objects. What you should do is to provide all the encoded parameters, converting the URL to string as follows:
// cyrillic characters are used in this example
let url = new URL('https://w3cdoc.com/Тест');
url.searchParams.set('key', 'ь');
console.log(url); //https://w3cdoc.com/%D0%A2%D0%B5%D1%81%D1%82?key=%D1%8A
You can notice that Тест inside the URL path and ъ inside the parameter are encoded. (您可以注意到, URL路径内的Тест和参数内的’被编码。)
How to Encode Strings
How to Encode Strings (如何对字符串进行编码)
Before the URL objects came out, strings were used for URLs. In modern programming, URL objects are handier. However, you can still use strings. The main asset of strings is that they make the code shorter. But, note that for using strings, it is necessary to encode and decode special characters manually. (在URL对象出来之前,字符串用于URL。 在现代编程中, URL对象更方便。 但是,您仍然可以使用字符串。 字符串的主要优点是它们使代码更短。 但是,请注意,要使用字符串,必须手动编码和解码特殊字符。)
Several built-in functions can be used for that. Among them are encodeURI, decodeURI, encodeURIComponent, and decodeURIComponent. To understand the difference between encodeURI and encodeURIComponent, let’s consider an example:
https://site.com:8080/path/page?p1=v1&p2=v2#hash
In the example above, it is not allowed to use in the URL characters like #, =,&, ?, :. So, the characters above should be encoded for not breaking the formatting. The encodeURI is used for encoding the characters that are completely prohibited in the URL. The encodeURIComponent function is used for encoding same characters, as well as #, =,&, ?, :, ,, +, ;, and @. EncodeURI can be used for the whole code like this:
// using cyrillic characters in url path
let url = encodeURI('http://site.com/здравствуйте');
console.log(url);
//http://site.com/%D0%B7%D0%B4%D1%80%D0%B0%D0%B2%D1%81%D1%82%D0%B2%D1%83%D0%B9%D1%82%D0%B5
But, for parameters, encodeURIComponent should be used instead:
let book = encodeURIComponent('Html&Css');
let url = `https://w3cdoc.com/search?s=${book}`;
console.log(url); // https://w3cdoc.com/search?s=Html%26Css