How to Get Query String Values in JavaScript

While working with JavaScript, it is often necessary to get query string values. In this snippet, we are going to provide you with several efficient solutions in case of getting a specific query string or all query strings.

How to get a specific query string

It is possible to get query string values by using pure JavaScript or jQuery. To implement that, create a function, such as getQueryParams and add the code given below:

Javascript get query string values
const getQueryParams = ( params, url ) => { let href = url; // this is an expression to get query strings let regexp = new RegExp( '[?&]' + params + '=([^&#]*)', 'i' ); let qString = regexp.exec(href); return qString ? qString[1] : null; }; console.log(getQueryParams('data','http://example.com?example=something&data=32'));

The function takes params and url as a parameters. Here you assign the url to variable href inside the function.

The Regex Pattern checks the value that starts with either & or ? followed by the parameter passed. It takes the value after = and stores it in queryString and returns it.

How to get all query strings

Getting all query strings differs from getting a single query string. Let’s see how you can solve this problem with the help of below code snippet:

Javascript get all query strings
const getQueryParams = (url) => { let qParams = {}; // create a binding tag to use a property called search let anchor = document.createElement('a'); // assign the href URL of the anchor tag anchor.href = url; // search property returns URL query string let qStrings = anchor.search.substring(1); let params = qStrings.split('&'); for (let i = 0; i < params.length; i++) { let pair = params[i].split('='); qParams[pair[0]] = decodeURIComponent(pair[1]); } return qParams; }; console.log(getQueryParams('http://example.com?example=something&data=24'));

Here to create an anchor element and use a property called search in the element. The search property returns the queryString completely.

After creating an anchor element and assigning the url to href, search returns the query strings of url. After doing all this stuff, you can get all the query parameters by splitting the string using the & keyword.