DEV Community

GaneshMani
GaneshMani

Posted on • Originally published at cloudnweb.dev

How to get Query String Parameters in Javascript - 2019

This series is a quick javascript tricks that you can learn in 2 mins. In this article, How to get Query String Parameters in Javascript - 2019.

There is a simple method to get the query string parameters in javascript.

const getQueryParams = ( params, url ) => {
  
  let href = url;
  //this expression is to get the query strings
  let reg = new RegExp( '[?&]' + params + '=([^&#]*)', 'i' );
  let queryString = reg.exec(href);
  return queryString ? queryString[1] : null;
};

getQueryParams('data','http://another-example.com?example=something&data=13');

Firstly, this function takes params and url as a parameters. Inside, the function we assign the url to varialble href.

After that, Regex Pattern checks the url to match a pattern. Mainly, regex checks the value that starts with either & or ? followed by the parameter that you pass.

Regex takes the value after symbol (=) and store it in the variable queryString and returns it.

Getting All Query Strings in Javascript

Above Implementation works fine if you want to get the specific query string. However, it will not work if you want to get all the query strings.

To get all the query strings from url, we can implement a different approach.


const getQueryParams = (url) => {
    let queryParams = {};
  //create an anchor tag to use the property called search
    let anchor = document.createElement('a');
  //assigning url to href of anchor tag
    anchor.href = url;
  //search property returns the query string of url
    let queryStrings = anchor.search.substring(1);
    let params = queryStrings.split('&');

    for (var i = 0; i < params.length; i++) {
        var pair = params[i].split('=');
        queryParams[pair[0]] = decodeURIComponent(pair[1]);
    }
    return queryParams;
};


getQueryParams('http://another-example.com?example=something&data=13');

Above all, the simplest way to solve this problem is to create an anchor element and use a property called search in anchor element. Search property returns the queryString completely.

Therefore, the above function takes url as a parameter. After that, we create an anchor element and assign the url to href.

After that, search method of anchor element returns the query strings of url.

As a result, we can get all the query parameters by splitting the string using keyword &.

Once you have the params in an Array, you can loop through it and get all the query strings that you want.

Reference,

How to get Query String Parameters in Javascript - 2019.

Get Query String Parameters with JavaScript

Top comments (6)

Collapse
 
daviddalbusco profile image
David Dal Busco • Edited

Is there any particular reason why you don't use the Web Apis URL or URLSearchParams ?

Collapse
 
ganeshmani profile image
GaneshMani

Though URLSearchParams works well for the usecase. i wanted to get all the query strings from the url which is difficult in URLSearchParams(from what i know). i wanted to write a custom function that i can use to get all query strings in the url.

Collapse
 
daviddalbusco profile image
David Dal Busco

Didn't tried out but it seems that URLSearchParams offers iterator to get all query strings.

From the doc:

URLSearchParams.entries()
Returns an iterator allowing iteration through all key/value pairs contained in this object.

URLSearchParams.keys()
Returns an iterator allowing iteration through all keys of the key/value pairs contained in this object.

Found out an example too: davidwalsh.name/query-string-javas...

That being said, the good point of your method is that it is compatible with Internet Explorer 😉

Thread Thread
 
ganeshmani profile image
GaneshMani

Cool.. Thanks for the update. i will add this in article.

Collapse
 
yalme profile image
Артём Пешков

IE 11 support only with polyfill.

Collapse
 
leye0 profile image
Léon Pelletier

console.log(Object.fromEntries(new URLSearchParams('?myVar=1&myOtherVar=2')));

Output:
{ myVar: "1", myOtherVar: "2" }