URLSearchParams
ℹ️ Use to easily work with a query string of URL.

Description

URLSearchParams defines utility method to work with the query string of a URL.

Example

Let's imagine we have an iframe that we configure with help of the query string inside this URL:
1
https://iframe.link/?id=123&locale=en_US&color=#2364AA
Copied!
Now we need to get our configuration and we can do the following:
1
const searchParams = new URLSearchParams(window.location.search);
2
​
3
const config = {
4
id: searchParams.get('id'), //-> 123
5
langauge: searchParams.get('locale'), //-> en_US
6
/* We also don't need to use decoding to get value with symbols 🔽 */
7
color: searchParams.get('color'), //-> #2364AA
8
};
9
​
10
// ✨ `URLSearchParams` interface allows to do more things:
11
/** Check if search parameter exists */
12
searchParams.has('id'); // true
13
/** Remove search parameter and it's value from the list */
14
searchParams.delete('id');
15
/** Append a specific key/value pair */
16
searchParams.append('title', 'Awesome Title');
17
/** Get string containing query string suitable to use in a URL */
18
searchParams.toString(); // language=english&color=&title=Awesome+Title
Copied!

Read More