solvit.io

Get the value of the query string parameters with JavaScript

function getQueryParameter(paramName)
{
    paramName = paramName.replace(/[\[\]]/g, '\\$&');
    var paramRegex = new RegExp('[?&]' + paramName + '(=([^&#]*)|&|#|$)');
    var paramAndValue = paramRegex.exec(window.location.href);

    if (!paramAndValue) return null;
    if (!paramAndValue[2]) return '';

    return decodeURIComponent(paramAndValue[2].replace(/\+/g, ' '));
}
Example
// Current URL is: http://example.org/foo/bar?foo1=bar1&foo2=&foo3
var value = getQueryParameter('foo1');
// value = 'bar1'

var value = getQueryParameter('foo2');
// value = '' (empty string because foo2 has no value)

var value = getQueryParameter('foo3');
// value = '' (empty string because foo3 has no value)

var value = getQueryParameter('foo4');
// value = null (because URL doesn't contain foo4 parameter)
Find more solutions about: , ,