0

How to get query string values in JavaScript?

Query string is the part of a URL which assigns values to specified parameters. There are several methods to retrieve query string in JavaScript:

Using Vanilla-JS (just pure JavaScript)
var getQueryStringByName = function(name, url) {
    if (!url) url = window.location.href;
    name = name.replace(/[\[\]]/g, '\\$&');
    
  	var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)')
    var results = regex.exec(url);
  
  
    if (!results) return null;
    if (!results[2]) return '';
  
    return decodeURIComponent(results[2].replace(/\+/g, ' '));
}

var url = 'https://coderatings.io?q=jquery&other=parameter';

console.log(getQueryStringByName('q', url));
console.log(getQueryStringByName('other', url));
RUN
ES2015 (ES6)
const getQueryStringParams = query => {
    return query
        ? (/^[?#]/.test(query) ? query.slice(1) : query)
            .split('&')
            .reduce((params, param) => {
                    let [key, value] = param.split('=');
      				key = /[?]/.test(key) ? key.split('?')[1] : key;
                    params[key] = value ? decodeURIComponent(value.replace(/\+/g, ' ')) : '';
                    return params;
                }, {}
            )
        : {}
};

const url = 'https://coderatings.io?q=jquery&other=parameter';
const params = getQueryStringParams(url);

console.log(params.q);
console.log(params.other);
RUN
URLSearchParams

The URLSearchParams is a special interface supported by most modern browsers to work with a query string of the URL.

const urlParams = new URLSearchParams('?q=jquery&other=parameter');

console.log(urlParams.get('q'));
console.log(urlParams.get('other'));
RUN
add comment
Suggest a different solution or add another example