Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the use of JavaScript's URL object

2025-03-04 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly introduces what is the use of JavaScript URL objects, with certain reference value, interested friends can refer to, I hope you have a lot of gains after reading this article, let Xiaobian take you to understand.

If we write our own code to parse and extract elements from URLs, it can be painful and cumbersome. Programmers, as one of the most lazy groups in society, are inevitably intolerable to endlessly build wheels, so most browsers have built-in URL objects in their standard libraries.

So now, with this, we can pass URL strings as arguments to URL constructors and create instances of it to parse URL content? The answer is: "yes! "。

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

1new URL www.grapecity.com.cn; In the code above, we created an instance of an absolute URL object. 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. It may be a bit awkward, but let's take a chestnut:

1new URL ('/developer','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 the following code in a similar way to chain definition:

123456789const 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 we used toString() for each argument, our execution would look like this:

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

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 be passed in only if the first parameter is a relative address. The string or URL object we pass in is converted to a USVString object that corresponds to a set of possible sequences of Unicode scalar values. In our code, we can think of them as regular strings. If both parameters are relative addresses, or if the base URL and relative address are invalid together, a TypeError exception is thrown. We can pass the URL object directly to the second argument because the URL object's toString method will convert the URL object to a full URL string before operating in the constructor.

URL objects can have the following attributes:

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

Hash attribute The hash attribute gets the part of the URL that follows the #sign. Because the string is not percentage decoded, special symbols such as the following are still encoded. They are encoded using the mapping below. During encoding, the characters on the left are converted to the characters on the right:

':' - %3A

'/' - %2F

'? ' - %3F

'#' - %23

'[' - %5B

']' - %5D

'@' - %40

'! ' - %21

'$' - %24

"'" - %27

'(' - %28

')' - %29

'*' - %2A

'+' - %2B

',' - %2C

';' - %3B

'=' - %3D

'%' - %25

' - %20 or +

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

12const 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. This property is a USVString that is converted to a string when we get it like above. Because it is not a read-only attribute, we can also assign it directly as in the following code:

1exampleUrl.hash = '#newHash'; for example:

123const 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 href attribute

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

12const exampleUrl = new URL ('http://huozige.grapecity.com.cn:8080/');console.log(exampleUrl.host); we get huozige.grapecity.com.cn:8080. As with other USVString properties, it is converted to a string when we retrieve it. Similarly, it is not a read-only property, so we can assign it the same as a hash property:

123const exampleUrl = new URL ('http://huozige.grapecity.com.cn:8080/featuredemo');exampleUrl.host ='es.grapecity.com.cn:80'; console.log(exampleUrl); This way we can also get new URLs.

Hostname attribute Using the hostname attribute, you can get the host name outside the port from the URL:

12const exampleUrl = new URL ('http://huozige.grapecity.com.cn:8080/featuredemo');console.log(exampleUrl.hostname) You can also modify the hostname attribute like any other attribute, for example:

1exampleUrl.hostname ='newExample.com'; Href attribute The href attribute of a URL object contains the entire address string of the incoming URL object, for example:

12const exampleUrl = new URL ('https://www.grapecity.com.cn/developer/spreadjs#price');console.log(exampleUrl.href); What is typed is what we pass to the URL constructor. Like other attributes, the href attribute is not read-only.

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

1234const 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) You will get

https://www.grapecity.com.cn

UserName & Password attributes UserName and Password attributes are also writable attributes, which can extract the contents of the username and password parts before the domain name, for example:

1234567const 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 attribute refers to obtaining the part of the URL passed in after the first slash (/) except parameters, for example:

12const url = new URL ("https://www.grapecity.com.cn/developer/spreadjs#price") console.log (url.pathname);Port property The Port property refers to the port value from which the incoming URL address can be obtained. This property is also writable.

12const url = new URL ('http://huozige.grapecity.com.cn:8080/function demonstrate');console.log(url.port);Protocol property can obtain the protocol name of the URL parameter passed in, generally referring to protocols such as http: , https: , ftp: , file: , etc.

12const url = new URL ('https://www.grapecity.com.cn/');console.log(url.protocol);Search property Can you get the URL parameter passed in? But this property only gets the whole query string, if you need to know the value of each parameter, you can use the searchParams property.

12const url = new URL('https://www.grapecity.com.cn:443? key1 =value1&key2= value2'); console.log (url.search);searchParams propertyThe search property simply fetches the entire parameter string for us, and if there is a way to parse the string into key-value pairs, then the searchParams property comes in handy, and this property gets a URLSearchParams object with the ability to list the query string key-value pairs, e.g., to get the parameter list, we can use it like this.

123const url = new URL(' https://www.grapecity.com.cn/? key1 =value1&key2= value2'); console.log (url.searchParams.get ('key 1')); console.log (url.searchParams.get ('key 2')); 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.

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

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

The URL.revokeObjectURL() method frees an object URL created by URL.createObjectURL(). This method is called when you have used the object URL and want the browser to know that the URL no longer needs to point to the corresponding file.

At the end of the summary, I bring you a table, hoping to help you better.

With URL objects, manipulating and extracting parts from URLs is no longer a pain because we don't have to write all the code ourselves to do the job. URL objects are built into the standard library of most browsers. Now we can pass the URL as a string to the URL constructor and create an instance of the URL. We can then use convenient value attributes and methods to manipulate and get the URL parts we want.

Thank you for reading this article carefully. I hope that Xiaobian's "What is the use of JavaScript URL objects" article will help everyone. At the same time, I hope that everyone will support you a lot and pay attention to the industry information channel. More relevant knowledge is waiting for you to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report