Mestika
8/29/2016 - 10:12 AM

Add Query String Parameter in JavaScript

Add Query String Parameter in JavaScript

/*
 * From
 * http://stackoverflow.com/questions/5999118/add-or-update-query-string-parameter
*/
function updateQueryStringParameter(uri, key, value) {
  var re = new RegExp("([?&])" + key + "=.*?(&|$)", "i");
  var separator = uri.indexOf('?') !== -1 ? "&" : "?";
  if (uri.match(re)) {
    return uri.replace(re, '$1' + key + "=" + value + '$2');
  }
  else {
    return uri + separator + key + "=" + value;
  }
}

var url = 'http://example.com/mypage?foo=bar';
var updatedUrl = updateQueryStringParameter(url, 'username', 'my-username');
console.log(updatedUrl);