How to Perform Javascript redirect url with by Preserving URL parameter of orignal URL?
eg
original url: http://test.com?a=1&b=2
Redirect to: http://sample.com?a=1&b=2
The following will get the current URL querystring:
var query = window.location.search;
That can then be used in the redirect:
window.location.replace('sample.com' + query);
Update
The .replace() method will remove the current URL from the browser history. If you want to retain the current URL use .assign() as mentioned by @igor
location.assign('sample.com' + location.search) if the redirect target needs to be saved in browser history.Modify the location object:
location.href = location.href.replace ( new RegExp("^" + "http://test.com"), "http://sample.com/" );
The statement replaces the start of the url from which the current document has been loaded. The resource from the new url will be loaded automatically.
Your sample urls do not contain path and fragment portions ( like in http://test.com/the/path/compon.ent?a=1&b=2#a_fragment). They are accessible as
location.pathname // 'http://test.com/the/path/compon.ent'
location.hash // '#a_fragment'
Note that the occurrence of these url components suggest to expressly compose the new url the way @MattSizzle outlines in his answer.