Thursday, February 6, 2014

JQuery URL parser function

// Parse URL Queries Method
(function($){
    $.getQuery = function( query ) {
        query = query.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
        var expr = "[\\?&]"+query+"=([^&#]*)";
        var regex = new RegExp( expr );
        var results = regex.exec( window.location.href );
        if( results !== null ) {
            return results[1];
            return decodeURIComponent(results[1].replace(/\+/g, " "));
        } else {
            return false;
        }
    };
})(jQuery);

// Document load
$(function(){
    var test_query = $.getQuery('test');
    alert(test_query); // For the URL /?test=yes, the value would be "yes"
});
Reference:

http://www.kevinleary.net/jquery-parse-url/

No comments:

Post a Comment