Saturday, 23 December 2017

Reading Query string Values in Javascript

Using simple javascript to get the  query string value of URL.


We have URL as 
<a href="DisplayContent.html?id=0"> 0</a>
<a href="DisplayContent.html?id=1">1</a>

To Read the content of URL you can use below method as;


function getParameterValueByName(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, " "));
    }





Calling this method in next page [DisplayContent]

var ist = getParameterValueByName('id');

Now lets see how we are getting Values.



1 comment: