📜  url - Javascript (1)

📅  最后修改于: 2023-12-03 14:48:14.121000             🧑  作者: Mango

URL - JavaScript

In this article, we will explore how to handle URLs in JavaScript. URLs or Uniform Resource Locators are addresses of resources on the web. In JavaScript, we can construct URLs, extract information from them and modify them using built-in tools and libraries.

Constructing a URL

To construct a URL in JavaScript, we can use the URL class. This class provides a clean interface for constructing and manipulating URLs. Here is an example:

const url = new URL('https://example.com/path/to/resource?param1=value1&param2=value2#fragment');

Here, we create a new URL object with the given URL string. We can access different parts of the URL using properties of this object. For example, to get the protocol (https), we can use the protocol property:

console.log(url.protocol); // 'https:'

We can also get the hostname (example.com) and port (null, since none was provided in the URL string):

console.log(url.hostname); // 'example.com'
console.log(url.port); // ''
Extracting Information from a URL

To extract information from a URL, we can use the properties of the URL object that we created earlier. For example, to get the query string (param1=value1&param2=value2), we can use the search property:

console.log(url.search); // '?param1=value1&param2=value2'

We can also get the hash (#fragment) using the hash property:

console.log(url.hash); // '#fragment'

To get the path (/path/to/resource), we can use the pathname property:

console.log(url.pathname); // '/path/to/resource'
Modifying a URL

To modify a URL, we can use the same URL object and set its properties to new values. For example, to change the protocol to http, we can do:

url.protocol = 'http:';
console.log(url.href); // 'http://example.com/path/to/resource?param1=value1&param2=value2#fragment'

We can also add or remove parameters from the query string. Here is an example of adding a new parameter (param3):

url.searchParams.set('param3', 'value3');
console.log(url.href); // 'http://example.com/path/to/resource?param1=value1&param2=value2&param3=value3#fragment'

We can remove a parameter by using the delete method:

url.searchParams.delete('param1');
console.log(url.href); // 'http://example.com/path/to/resource?param2=value2&param3=value3#fragment'
Conclusion

In this article, we learned how to handle URLs in JavaScript. We saw how to construct a URL using the URL class, how to extract information from a URL using its properties, and how to modify a URL by setting its properties or using the URLSearchParams interface. URLs are an integral part of the web, and understanding how to handle them is a crucial skill for any web developer.