Shravan Kumar Kasagoni

Skip Navigation
URLSearchParams returning null for the first query string

URLSearchParams returning null for the first query string

 /  Leave a response

The URLSearchParams interface defines utility methods to work with the query string of a URL.


const url = 'http://example.com?orderNumber=123456&pageSize=20';

const urlSearchParams = new URLSearchParams(url);

console.log(urlSearchParams.get('orderNumber')); //result: null

console.log(urlSearchParams.get('pageSize')); //result: 20

As shown in the above code snippet, it won’t work as expected if you directly use the URL string in the URLSearchParams constructor. So the result of the first query string will always be null.

You need to do the following. First, initialize the URL constructor using the url string, then pass the search property of the URL object to the URLSearchParams constructor.


const url = new URL('http://example.com?orderNumber=123456&pageSize=20');

const urlSearchParams = new URLSearchParams(url.search);

console.log(urlSearchParams.get('orderNumber')); //result: 123456

console.log(urlSearchParams.get('pageSize')); //result: 20

Happy Coding!

Write a response

Your email address will not be published. Required fields are marked *

All code will be displayed literally.