Created
June 12, 2023 15:10
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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¶m2=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