Let's talk about what JavaScript's URL object is

Let's talk about what JavaScript's URL object is

Overview

If we write our own code to parse and extract elements from a URL, it can be painful and cumbersome. Programmers are one of the laziest groups in this society, and endlessly reinventing the wheel is bound to be intolerable, so most browsers have built-in URL objects in their standard libraries.

So now, with it, we can pass the URL string as a parameter to the URL constructor and create an instance of it to parse the URL content? The answer is: "Yes!".

To create a URL object using the URL constructor, we use new in the following code:

new URL('https://www.grapecity.com.cn');

In the above code, we create an instance of the URL object with an absolute address. But at the same time, we can also pass in a relative address as the first parameter and the base URL of the relative address as the second parameter to create a URL object. This may be a bit difficult to understand, so let’s take an example:

new URL('/developer', 'https://www.grapecity.com.cn');

Looking at the code above, the second base URL parameter must be a valid absolute address, not a relative address fragment. It must start with http:// or https://. We can also use it in a chain-like manner in the following code:

const gcUrl = 'https://www.grapecity.com.cn/';
const gcDevUrl = new URL("/developer", gcUrl);
const gcUrl2 = new URL(gcUrl);
const gcSlnUrl = new URL('/solutions', gcUrl2);
const Url = new URL('aboutus', gcSlnUrl);

If each parameter uses toString(), our execution results should be as follows:

https://www.grapecity.com.cn/developer

https://www.grapecity.com.cn/

https://www.grapecity.com.cn/solutions

https://www.grapecity.com.cn/aboutus

The second parameter is optional and should only be passed if the first parameter is a relative address. The string or URL object we pass in is converted to a USVString object, which corresponds to the set of possible sequences of Unicode scalar values. In our code, we can treat them as regular strings. If both arguments are relative URLs, or if both the base URL and the relative URL are invalid, a TypeError exception is thrown. We can pass the URL object directly to the second parameter because the URL object's toString method will convert the URL object into a complete URL string before operating on it in the constructor.

URL objects can have the following properties:

Hash, host, hostname, href, origin, username/password, pathname, port, protocol, search and other attributes. Next, let’s learn about them together!

Hash Properties

The hash attribute can get the part of the URL after the # sign. Since the string is not percent-decoded, special symbols like below are still encoded. They are encoded using the following mapping. During encoding, characters on the left are converted to characters on the right:

':' — %3A

'/' — %2F

'?' — %3F

'#' - %twenty three

'[' — %5B

']' — %5D

'@' — %40

'!' - %twenty one

'$' — %24

“'“ — %27

'(' — %28

')' — %29

'*' — %2A

'+' — %2B

',' — %2C

';' — %3B

'=' — %3D

'%' — %25

' ' — %20 or +

For example, we have a URL string like this, https://www.grapecity.com.cn/developer/spreadjs#price, and then we can directly take out the Hash attribute value as follows:

const exampleUrl = new URL('https://www.grapecity.com.cn/developer/spreadjs#price');
console.log(exampleUrl.hash);

In the run result, we get '#price' in the console.log statement. The property is a USVString and when we get it like above it is converted to a string. Because it is not a read-only property, we can also assign a value to it directly as shown in the following code:

exampleUrl.hash = '#newHash';

For example:

const exampleUrl = new URL('https://www.grapecity.com.cn/developer/spreadjs#price');
exampleUrl.hash = '#newPrice';
console.log(exampleUrl.hash);

We can get the updated URL https://www.grapecity.com.cn/developer/spreadjs#newHash through the href attribute

Host property

The host property of a URL object is a USVString containing the host name. If the port is included after the :, then we will also get the port number of the host. For example, if we have:

const exampleUrl = new URL('http://huozige.grapecity.com.cn:8080/');
console.log(exampleUrl.host);

We can get huozige.grapecity.com.cn:8080. Like other USVString properties, it is converted to a string when we retrieve it. Likewise, it is not a read-only property, so we can assign values ​​to it like a hash property:

const exampleUrl = new URL('http:// huozige.grapecity.com.cn:8080/功能演示');
exampleUrl.host = 'es.grapecity.com.cn:80';
console.log(exampleUrl);

This way we can also get a brand new URL.

Hostname Attribute

Using the hostname property, you can get the hostname in addition to the port from the URL:

const exampleUrl = new URL('http:// huozige.grapecity.com.cn:8080/功能演示');
console.log(exampleUrl.hostname)

You can also modify the hostname property like any other property, for example:

exampleUrl.hostname = 'newExample.com';

Href Attribute

The href attribute of the URL object contains the entire address string passed into the URL object, for example:

const exampleUrl = new URL('https://www.grapecity.com.cn/developer/spreadjs#price');
console.log(exampleUrl.href);

What is printed out is the content we passed to the URL constructor. Like other attributes, the href attribute is not read-only.

Origin properties

Different from other properties, Origin is a read-only property that will return you the Unicode serialized USVString with the URL origin. The structure of Origin is determined by the type of URL passed in. For http or https links, the Origin will be the protocol (http/https) + (://) + domain name + (:port). In general, the default port will be ignored. For BLOB links, Origin returns the part after BLOB:. For example:

const url1 = new URL("https://www.grapecity.com.cn/:443")
const url2 = new URL("blob:https://www.grapecity.com.cn/:443")
console.log(url1.origin);
console.log(url2.origin)

UserName & Password Properties

The UserName and Password properties are also writable properties that can extract the username and password parts before the domain name, for example:

const url = new URL('https://username:password@www.grapecity.com.cn');
console.log(url.username);
console.log(url.password);

url.username = "username1";
url.password = "password1";
console.log(url.username);
console.log(url.password);

Pathname Attribute

This property is to get the part after the first slash (/) of the incoming URL except the parameters, for example:

const url = new URL ("https://www.grapecity.com.cn/developer/spreadjs#price")
console.log(url.pathname);

Port Properties

The Port property refers to the port value that can be used to obtain the incoming Url address. This property is also writable.

const url = new URL('http://huozige.grapecity.com.cn:8080/功能演示');

console.log(url.port);

Protocol Properties

You can get the protocol name of the incoming Url address parameter, which generally refers to protocols such as http:, https:, ftp:, file:, etc.

const url = new URL('https://www.grapecity.com.cn/');

console.log(url.protocol);

Search Attributes

Can I get the incoming Url address parameters? However, this property can only obtain the entire query string. If you need to know the value of each parameter, you can use the searchParams property.

const url = new URL('https://www.grapecity.com.cn:443?key1=value1&key2=value2');

console.log(url.search);

searchParams Property

The search property only gets us the entire parameter string. If we need to parse the string into key-value pairs, the searchParams property comes in handy. This property will get a URLSearchParams object, which has the ability to list the query string key-value pairs. For example, to get the parameter list, we can use it like this.

const url = new URL('https://www.grapecity.com.cn/?key1=value1&key2=value2');
console.log(url.searchParams.get('key1'));
console.log(url.searchParams.get('key2'));

You get value1 from the first console.log statement and value2 from the second console.log statement. The URLSearchParams object has a get method that gets the value of a given query string key by key name.

Static methods

There are 2 static methods in the URL constructor, it has createObjectURL() method and revokeObjectURL() method.

The URL.createObjectURL() static method creates a DOMString containing a URL representing the object given as a parameter. The lifecycle of this URL is tied to the document in the window in which it was created. This new URL object represents the specified File object or Blob object.

The URL.revokeObjectURL() method releases an object URL created by URL.createObjectURL(). You need to call this method when you have used this object URL and want to let the browser know that this URL no longer points to the corresponding file.

Summarize

Finally, I bring you a table, I hope it can help you better understand

With the URL object, manipulating and extracting parts from a URL is no longer a painful task because we don't have to write all the code to do this ourselves. Most browsers have a URL object built into their standard libraries. Now we can pass the URL as a string to the URL constructor and create an instance of URL. We can then use the convenient value properties and methods to manipulate and get the part of the URL we want.

You may also be interested in:
  • Writing Maintainable Object-Oriented JavaScript Code
  • Using JavaScript to create maintainable slideshow code
  • Detailed explanation of the practical application of regular expressions in JavaScript
  • How to implement an array lazy evaluation library in JavaScript
  • Detailed explanation of the command mode in Javascript practice
  • How to make your own native JavaScript router
  • How to Learn Algorithmic Complexity with JavaScript
  • Use a few interview questions to look at the JavaScript execution mechanism
  • Teach you how to write maintainable JS code

<<:  Summary of the differences between count(*), count(1) and count(col) in MySQL

>>:  Complete steps to upgrade Nginx http to https

Recommend

MySQL turns off password strength verification

About password strength verification: [root@mysql...

Perfect solution to Google Chrome autofill problem

In Google Chrome, after successful login, Google ...

Detailed discussion of InnoDB locks (record, gap, Next-Key lock)

Record lock locks a single index record. Record l...

Sample code for using CSS to write a textured gradient background image

The page length in the project is about 2000px or...

Solution to the problem that Docker container cannot access Jupyter

In this project, the Docker container is used to ...

How to set background blur with CSS

When making some pages, in order to make the page...

Several ways to shut down Hyper-V service under Windows 10

When using VMware Workstation to open a virtual m...

JavaScript Shorthand Tips

Table of contents 1. Merge arrays 2. Merge arrays...

How to install Nginx in Docker

Install Nginx on Docker Nginx is a high-performan...

Summary of HTML knowledge points for the front end (recommended)

1. HTML Overview htyper text markup language Hype...

Sharing ideas on processing tens of millions of data in a single MySQL table

Table of contents Project Background Improvement ...