Skip to content

Instantly share code, notes, and snippets.

@niyazpk
Created October 25, 2014 14:03
Show Gist options
  • Save niyazpk/f8ac616f181f6042d1e0 to your computer and use it in GitHub Desktop.
Save niyazpk/f8ac616f181f6042d1e0 to your computer and use it in GitHub Desktop.
Add or update query string parameter
// Add / Update a key-value pair in the URL query parameters
function updateUrlParameter(uri, key, value) {
// remove the hash part before operating on the uri
var i = uri.indexOf('#');
var hash = i === -1 ? '' : uri.substr(i);
uri = i === -1 ? uri : uri.substr(0, i);
var re = new RegExp("([?&])" + key + "=.*?(&|$)", "i");
var separator = uri.indexOf('?') !== -1 ? "&" : "?";
if (uri.match(re)) {
uri = uri.replace(re, '$1' + key + "=" + value + '$2');
} else {
uri = uri + separator + key + "=" + value;
}
return uri + hash; // finally append the hash as well
}
@chenyuantao
Copy link

Typescript version

Tweaked code: https://gist.github.com/niyazpk/f8ac616f181f6042d1e0#gistcomment-3461639

Thanks all to those improving this, pass it on 👍

const updateUrlParameter = (uri: string, key: string, value: string | null) => {
  // remove the hash part before operating on the uri
  const i = uri.indexOf('#');
  const hash = i === -1 ? '' : uri.substr(i);
  uri = i === -1 ? uri : uri.substr(0, i);

  const re = new RegExp(`([?&])${key}=.*?(&|$)`, 'i');
  const separator = uri.indexOf('?') !== -1 ? '&' : '?';

  if (value === null) {
    // remove key-value pair if value is specifically null
    uri = uri.replace(new RegExp(`([?&]?)${key}=[^&]*`, 'i'), '');
    if (uri.slice(-1) === '?') {
      uri = uri.slice(0, -1);
    }
    // replace first occurrence of & by ? if no ? is present
    if (uri.indexOf('?') === -1) uri = uri.replace(/&/, '?');
  } else if (uri.match(re)) {
    uri = uri.replace(re, `$1${key}=${value}$2`);
  } else {
    uri = `${uri + separator + key}=${value}`;
  }
  return uri + hash;
};

@Leksat
Copy link

Leksat commented Aug 24, 2021

It worth to publish it on NPM. I was really surprised today that there is no package to manipulate non-absolute URLs 😅

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment