How I get query string values in JavaScript?

Today i am going to show you, how you can get string values by using JavaScript ?. Yes you can do it by using pure JavaScript, you do not need any JavaScript Plugin or library for this task. JavaScript have some build-in method for getting query string values. Here is the code of JavaScript by following this you can easily handle query values in JavaScript.

function getParameterByName(name, url) {
    if (!url) url = window.location.href;
    name = name.replace(/[\[\]]/g, “\\$&”);
    var regex = new RegExp(“[?&]” + name + “(=([^&#]*)|&|#|$)”),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return ”;
    return decodeURIComponent(results[2].replace(/\+/g, ” “));
}

How you can use this code?

// query string: ?foo=lorem&bar=&baz
var foo = getParameterByName(‘foo’); // “lorem”
var bar = getParameterByName(‘bar’); // “” (present with empty value)
var baz = getParameterByName(‘baz’); // “” (present with no value)
var qux = getParameterByName(‘qux’); // null (absent)

You will get  the first value even there are several values are present in Url.

About Moazzam Qureshi

I am SEO expert and web developer since 2011. My hobby is to write & provides quality content about blogging, SEO , Social Media , Earn Online and Affiliate Marketing.