URL Objects

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 .

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:

new URL(url, [base])

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:

let url1 = new URL('https://w3docs.com/admin');
let url2 = new URL('/admin', 'https://w3docs.com');
console.log(url1); // https://w3docs.com/admin
console.log(url2); // https://w3docs.com/admin

A new URL can be generated on the basis of the existing ones:

let url = new URL('https://w3docs.com/tester');
let newUrl = new URL('tester', url);
console.log(newUrl); // https://w3docs.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://w3docs.com/url');
console.log(url.protocol); // https:
console.log(url.host); // w3docs
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

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://w3docs.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://w3docs.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

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://w3docs.com/Тест');
url.searchParams.set('key', 'ь');
console.log(url); //https://w3docs.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.

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:

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://w3docs.com/search?s=${book}`;
console.log(url); // https://w3docs.com/search?s=Html%26Css



Do you find this helpful?

Related articles