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.
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:
Here is how an example of a URL looks like:
let url = new URL('https://w3docs/admin');
Now, let’s check out two URLs that are equivalent:
A new URL can be generated on the basis of the existing ones:
It is possible to access the URL components at once. Hence, it allows parsing the URL like this:
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
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:
About the Encoding of URLs
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:
You can notice that Тест inside the URL path and ъ inside the parameter are encoded.
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.
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:
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:
But, for parameters, encodeURIComponent should be used instead: