Sandeep
Sandeep

Reputation: 967

How to Perform Javascript redirect url with by Preserving URL parameter

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

Upvotes: 3

Views: 5698

Answers (2)

collapsar
collapsar

Reputation: 17238

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.

Upvotes: 2

MattSizzle
MattSizzle

Reputation: 3175

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

Upvotes: 7

Related Questions