By Sam Deering

jQuery add param to url function

By Sam Deering
Help us help you! You'll get a... FREE 6-Month Subscription to SitePoint Premium Plus you'll go in the draw to WIN a new Macbook SitePoint 2017 Survey Yes, let's Do this It only takes 5 min

This jQuery utility function checks if a paramter is present in the current page URL and if it doesn’t exist it adds it and returns the url in full. Could be useful if you needed to do an ajax request to update a database with new form data and simply want to redirect to the same url but with an updated flag to show an updated box.



    var JQUERY4U = {};

          * Add a parameter to url if doesn't already exist
          * @param param - the parameter to add
          * @param value - the value of the parameter
          * @return url - the url with the appended parameter
        addParamToUrl: function(param, value)
            //check if param exists
            var result = new RegExp(param + "=([^&]*)", "i").exec(;
            result = result && result[1] || "";

            //added seperately to append ? before params
            var loc = W.location;
            var url = loc.protocol + '//' + + loc.pathname +;

            //param doesn't exist in url, add it
            if (result == '')
                //doesn't have any params
                if ( == '')
                    url += "?" + param + '=' + value;
                    url += "&" + param + '=' + value;

            //return the finished url
            return url;

    //example usage
    var updatedUrl = JQUERY4U.UTIL.addParamToUrl('updated', 'true');

})(jQuery, window, document);
Login or Create Account to Comment
Login Create Account
Get the most important and interesting stories in tech. Straight to your inbox, daily.Is it good?