Some wonderful uses of URL objects in JavaScript

Some wonderful uses of URL objects in JavaScript

Preface

The URL object may be used less frequently on the page side. Generally speaking, most of the operations on the URL on the page side are to parse URL parameters. There are many libraries to choose from for parsing URL parameters, such as qs, or use the browser's native URLSearchParams

// Assume the current url is 'https://www.test.com?a=1&b=2'
const b = new URLSearchParams(location.search);
const aParam = b.get('a'); // 1
const bParam = b.get('b'); // 2
const entries = [...b];
// [['a', '1'], ['b', '2']]
// If you want to get an object like qs.parse, you can do this const params = Object.fromEntries(entries);
// {a: 'c', b: '2'}

Parsing parameters

Parsing parameters through URLSearchParams does not seem to be closely related to the URL object, but you can look at the object returned after the URL object is instantiated.

const a = new URL('https://www.test.com?a=1&b=2');
// hash: ""
// host: "www.test.com"
// hostname: "www.test.com"
// href: "https://www.test.com/?a=1b=2"
// origin: "https://www.test.com"
// password: ""
// pathname: "/"
// port: ""
// protocol: "https:"
// search: "?a=1&b=2"
// searchParams: URLSearchParams {}
// username: ""
// [[Prototype]]: URL

From the returned object, we can see that after the URL is instantiated, the returned attribute searchParams is actually an instantiated URLSearchParams object. So there is actually another way to get the parameters through the URL object. For example, the above operation can be changed to

const a = new URL('https://www.test.com?a=1&b=2');
const entries = [...a.searchParmas];
const params = Object.fromEntries(entries);

// In the browser console, one line [...new URL(location.href).searchParams];

Modify URL parameters

There is no need to use URL for parsing parameters. It is sufficient to use URLSearchParams object. So what else can be done with URL object? Actually, we can think about that URLSearchParams provides write operations such as set and append. At the same time, the properties returned by URL object can also be modified. Can we modify a URL or generate a URL by modifying the parameters in the URL? After all, many times, the modification of URL stays at string operation, which is also dangerous and easy to report errors.

const a = new URL('https://www.test.com?a=1&b=2');
a.searchParams.set('a', '18');
a.searchParams.set('b', '14');
a.searchParams.set('c', 'test');
let newURL = a.toString(); // https://www.test.com/?a=18&b=14&c=test
a.hash = 'hasha';
newURL = a.toString(); // 'https://www.test.com/?a=18&b=14&c=test#hasha'
a.host = 'www.init.com';
newURL = a.toString(); // https://www.init.com/?a=18&b=14&c=test#hasha

Summarize

The URL object is quite convenient in operating URLs. A simple encapsulation can save a lot of packages. With some workarounds, the URL can be modified in reverse. This object can be used in the browser, but there may be compatibility issues. If it is on the desktop, you can use it with confidence (what is IE). If it is on the mobile terminal, you may need to configure polyfill. This object can also be used in deno

This concludes this article about some wonderful uses of JavaScript URL objects. For more relevant content on the wonderful uses of JavaScript URL objects, please search for previous articles on 123WORDPRESS.COM or continue to browse the related articles below. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • JavaScript data transmission between different pages (URL parameter acquisition)
  • How to remove jsessionid after URL in Springboot
  • vue.js downloads pictures according to picture url
  • JavaScript library urlcat URL builder library

<<:  HTML basic structure_Powernode Java Academy

>>:  Detailed explanation of how to deploy and install the Chinese version of Redash in Docker

Recommend

Example code for achieving hollowing effect with pure CSS

I have recently studied the hollowing effect. bac...

How to install a virtual machine with Windows services on Mac

1. Download the virtual machine Official download...

Implementation of Vue large file upload and breakpoint resumable upload

Table of contents 2 solutions for file upload Bas...

A few steps to easily build a Windows SSH server

The SSH mentioned here is called Security Shell. ...

Solution to MySQL root password error number 1045

Stop MySQL Service Windows can right-click My Com...

Significantly optimize the size of PNG images with CSS mask (recommended)

This article is welcome to be shared and aggregat...

MySQL insert json problem

MySQL 5.7.8 and later began to support a native J...

Detailed explanation of how to view MySQL memory usage

Preface This article mainly introduces the releva...

Turn off the AutoComplete function in the input box

Now we can use an attribute of input called autoco...

Summary of MySQL InnoDB architecture

Table of contents introduction 1. Overall archite...

How to implement scheduled backup of CentOS MySQL database

The following script is used for scheduled backup...

MySQL cleverly uses sum, case and when to optimize statistical queries

I was recently working on a project at the compan...

WebWorker encapsulates JavaScript sandbox details

Table of contents 1. Scenario 2. Implement IJavaS...