How to Get URL Parameters in Javascript

URL Parameters

This is great question solution for How to Get URL Parameters in Javascript. Now get URL parameters using 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.

Also Read: Javascript Interview Question answer

 

Here is function for Get URL Parameters in Javascript

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.findyoursolution.in/?category=PHP&tag=File-uploading&author=jitesh";
var category = getParameter('category', url); // PHP
var tag = getParameter('tag', url); // File-uploading
var author = getParameter('author', url); // Rohit

Leave a Reply