Skip to content

Instantly share code, notes, and snippets.

@ahmu83
Created June 12, 2023 15:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ahmu83/cc62a377173c3dd1fe0052cbc44e9d47 to your computer and use it in GitHub Desktop.
Save ahmu83/cc62a377173c3dd1fe0052cbc44e9d47 to your computer and use it in GitHub Desktop.
Function to redirect to a url with the all the current URL params
/**
* Function to redirect to a url with the all the current URL params
*
* @param string url
* @param object params
* @param boolean dontCarryParams
*
* usage:
* redirect('http://example.com', {param1: 111, param2: 222})
* will redirect to http://example.com/?param1=111&param2=222
*
*/
function redirect(url, params = {}, dontCarryParams = false) {
params = typeof params === 'object' ? params : {};
params = dontCarryParams === true ? {} : params;
var currentParams = Object.fromEntries(new URLSearchParams(window.location.search));
var allParams = new URLSearchParams({ ...currentParams, ...params });
var allParamsStr = allParams.toString();
var redirectUrl = url;
redirectUrl += allParamsStr ? (url.includes('?') ? '&' : '?') : '';
redirectUrl += allParams.toString();
window.location = redirectUrl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment