Skip to content

Instantly share code, notes, and snippets.

@dartmax
Last active October 13, 2020 16:17
Show Gist options
  • Select an option

  • Save dartmax/6759bfb8ff668202e5276c98d966f168 to your computer and use it in GitHub Desktop.

Select an option

Save dartmax/6759bfb8ff668202e5276c98d966f168 to your computer and use it in GitHub Desktop.
Add a query string parameter to the url if not present, or if it present, update the current value
export const updateQueryStringParameter = (uri, key, value) => {
const re = new RegExp(`([?&])${key}=.*?(&|$)`, 'i');
const separator = uri.indexOf('?') !== -1 ? '&' : '?';
if (uri.match(re)) {
return uri.replace(re, `$1${key}=${value}$2`);
}
return `${uri + separator + key}=${value}`;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment