How to Get URL Parameters in Javascript

This is small set of code snippet to get url parameters in javascript, Getting URL’s parameter in client side language like javascript is not as easy in server side language. So you have to write manually program in javascript which extract URL’s parameter and you can easily access by it’s name.



Here is the function.

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




The above function written in pure javascript you only need to pass parameter name which you want to extract and URL, If URL is not set it’ll automatically set current URL, With the help of RegExp and decodeURIComponent function in javascript it return query string by it’s name. See example.

var url = "http://www.iamrohit.in/?category=PHP&tag=File-uploading&author=Rohit";
var category = getParameter('category', url); 
var tag = getParameter('tag', url); 
var author = getParameter('author', url); // Rohit