Javascript: Add URL parameter

Here’s a handy function for adding a new parameter to a URL:

function addUrlParam(param, value)
{
   var url = location.href;
   if (location.search.indexOf(param) != -1) return url;
   var hash = location.hash, sep = url.indexOf('?') == -1 ? '?' : '&';
   return url.replace(hash,'') + sep + encodeURIComponent(param) + (value ? '=' + encodeURIComponent(value) : '') + hash;
}

Leave a Reply

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

*
*
Website