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

MySQL master-slave replication configuration process

Main library configuration 1. Configure mysql vim...

How to use Linux to calculate the disk space occupied by timed files

Open the scheduled task editor. Cent uses vim to ...

The final solution to Chrome's minimum font size limit of 12px

I believe that many users who make websites will ...

CSS sets the list style and creates the navigation menu implementation code

1. Set the list symbol list-style-type: attribute...

A brief discussion on the magic of parseInt() in JavaScript

cause The reason for writing this blog is that I ...

MySQL restores data through binlog

Table of contents mysql log files binlog Binlog l...

Ideas and codes for implementing Vuex data persistence

What is vuex vuex: is a state manager developed s...

Detailed explanation of the use of Linux time command

1. Command Introduction time is used to count the...

Implementation code of jquery step progress axis plug-in

A jQuery plugin every day - step progress axis st...

The use of anchor points in HTML_PowerNode Java Academy

Now let's summarize several situations of con...

How to run py files directly in linux

1. First create the file (cd to the directory whe...

Discussion on the problem of iframe node initialization

Today I suddenly thought of reviewing the producti...

VMware + Ubuntu18.04 Graphic Tutorial on Building Hadoop Cluster Environment

Table of contents Preface VMware clone virtual ma...

Explanation of the problem that JavaScript strict mode does not support octal

Regarding the issue that JavaScript strict mode d...