Get URL Parameters using jQuery and JavaScript

Most PHP apps use parameters to query data. There are many cases you have to handle these parameters on front-end, hence JavaScript or jQuery is used. Actually, jQuery isn’t necessary in this case. Below are small code snippets which can help you retrieve any parameters in a URL.

Get parameters from current URL:

//if URL contains '?test=true'
var isTest = getCurrentURLParamValue('test');
function getCurrentURLParamValue(param){
    var urlParams = window.location.search.substring(1);
    var urlParamsArray = urlParams.split('&');
    for (var i = 0; i < urlParamsArray.length; i++){
        var urlParamName = urlParamsArray[i].split('=');
        if (urlParamName[0] == param){
            return urlParamName[1];
        }
    }
}

Get parameters from any given URL:

//if URL contains '?test=false&title=A+Test+Title'
var isTest = getURLParamValue('http://www.example.com/index.php?test=false&title=A+Test+Title', 'test');
var title = getURLParamValue('http://www.example.com/index.php?test=false&title=A+Test+Title', 'title');

function getURLParamValue(url, param){
    var results = new RegExp('[\?&]' + param + '=([^&#]*)').exec(url);
    if (results != null){
       return decodeURIComponent(results[1]);
    } else{
       return null;
    }
}

Leave a Comment

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

We care about your privacy and data security. Google serves cookies to analyse traffic and show ads on this site. By using this site you agree to these cookies being set. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close