3

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

2 Answers 2

7

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);

DOCS

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

Sign up to request clarification or add additional context in comments.

1 Comment

Or location.assign('sample.com' + location.search) if the redirect target needs to be saved in browser history.
2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.