Get URL parameters using jQuery

jQuery code snippet to get the dynamic variables stored in the url as parameters and store them as JavaScript variables ready for use with your scripts. Used differently to Hash Url’s as the world turns to dynamic web apps. Thus things like Decoding URL Strings will be ever-popular for years to come.

$.urlParam = function(name){
 var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
 return results[1] || 0;
}

// example.com?param1=name&param2=&id=6
$.urlParam('param1'); // name
$.urlParam('id');        // 6
$.urlParam('param2');   // null

//example params with spaces
http://www.jquery4u.com?city=Gold Coast
console.log($.urlParam('city'));  
//output: Gold%20Coast

console.log(decodeURIComponent($.urlParam('city')));  
//output: Gold Coast
This could be used for example to set the default value of a text input field:
$('#city').val(decodeURIComponent($.urlParam('city')));
Thanks to bjverde for improvements to this function:
$.urlParam = function(name){
    var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
    if (results==null){
       return null;
    }
    else{
       return results[1] || 0;
    }
}

Comments

Popular posts from this blog

My Response is on my own Website : Best Quality Backlink Strategy

disk tv connection near agam singh nagar siliguri

Why is Digital Marketing Important? What are the Advantages of Digital Marketing?