LA_
LA_

Reputation: 20409

How to generate correct url for window.location.href?

How to generate correct url for window.location.href in the following two scenarios:

  1. current url is http://example.com:8080/something/
  2. current url is http://example.com:8080/something/something-else/

target url is http://example.com:8080/something/something-new/.

Ideally I would like to have the same code for both scenarios and http://example.com:8080/something/ should not be hardcoded.

Upvotes: 0

Views: 1375

Answers (2)

bozdoz
bozdoz

Reputation: 12860

Could you do:

window.location.href="/something/something-new/";

Upvotes: 0

GolezTrol
GolezTrol

Reputation: 116100

You can't without somehow hardcoding (or softcoding) the path. You will need a root path, to know how many directories you need to go up (either 0 or 1) before you can add something-new to the path. If you got a server side scripting language, you can calculate it or define it in a setting, and then output the path so it's available in Javascript.

Upvotes: 1

Related Questions