How to get Query String Values using URLSearchParams in JavaScript

Updated onbyAlan Morel
How to get Query String Values using URLSearchParams in JavaScript

One of the most common ways for a browser to send data to a server is by appending it to the URL. For example, if you wanted to send the name and age of a user to a server, you might do something like this:

BASH
https://example.com?name=John&age=21

JavaScript has built-in APIs to help you work with query strings.

In this post, we'll learn how we can test if a string contains a specific search param and how to get the value.

How to test if a string contains a search param

JavaScript provides the class URLSearchParams to help us work with query strings. It has a method called has() that we can use to test if a string contains a specific search param.

First let's create a new URL object:

JAVASCRIPT
const url = new URL("https://example.com?name=John&age=21");

Now let's take the search params using the search property, then parse them by passing them to the URLSearchParams constructor:

JAVASCRIPT
const url = new URL("https://example.com?name=John&age=21"); const params = new URLSearchParams(url.search);

From here, we can now use the has method that will check if the specific param exists:

JAVASCRIPT
const url = new URL("https://example.com?name=John&age=21"); const params = new URLSearchParams(url.search); console.log(params.has("name")); console.log(params.has("age")); console.log(params.has("location"));
BASH
true true false

How to get the value of a search param

We've seen how to test if a string contains a specific search param. Now let's see how we can get the value of a search param.

Like before, we can define a new URL, get its search params, then parse them:

JAVASCRIPT
const url = new URL("https://example.com?name=John&age=21"); const params = new URLSearchParams(url.search);

Now, we can use the get method to get the value of a specific search param:

JAVASCRIPT
const url = new URL("https://example.com?name=John&age=21"); const params = new URLSearchParams(url.search); console.log(params.get("name")); console.log(params.get("age")); console.log(params.get("location"));
BASH
John 21 null

Alternatively, you can also iterate over the search params using the forEach method:

JAVASCRIPT
const url = new URL("https://example.com?name=John&age=21"); const params = new URLSearchParams(url.search); params.forEach((value, key) => { console.log(`${key}: ${value}`); });
BASH
name: John age: 21

Conclusion

In this post, we learned how to test if a string contains a specific search param and how to get the value.

Simply use the has method on the URLSearchParams class to test if a string contains a specific search param, and the get method to get the value.

Thanks for reading!

To learn more about web development, founding a start-up, and bootstrapping a SaaS, follow me on X!
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.