IT & Programming

Get query string value with JavaScript

A custom made simplified function to catch query string parameter value with JavaScript. All you have to do is to pass the name of the query string parameter and optionally the URL.

Function

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

Calling The Function

alert(getParameterByName('id'));

Leave A comment

Email address is optional and will not be published. Only add email address if you want a reply from blog author.
Please fill required fields marked with *