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); // PHP
var tag = getParameter('tag', url); // File-uploading
var author = getParameter('author', url); // Rohit



2 Replies to “How to Get URL Parameters in Javascript”

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.