window.location
works fine, but returns me the whole, absolute path, like http://domain.xyz/punch/lines
. But I only need http://domain.xyz/
. How can I extract only that first part? And how can I make that dynamic, I mean to be always the same even when the subdirectory path gets longer?
Asked
Active
Viewed 1e+01k times
37

leymannx
- 5,138
- 5
- 45
- 48
4 Answers
80
You can get the protocol and the host separately, and then join them to get what you need
window.location.protocol + "//" + window.location.host + "/"
As a sidenote, window.location.pathname
would contain the path.

adeneo
- 312,895
- 29
- 395
- 388
-
Thanks for your answer but is it supported in most browsers like firefox (i have checked it), chrome, ie (8,9,10) and safari? – Smile Jan 07 '14 at 05:21
-
@NullPointer - Should be supported in all browsers – adeneo Jan 07 '14 at 08:09
3
Try this:
location.protocol + "//" + location.host

Dharmesh Patel
- 1,881
- 1
- 11
- 12
-
-
Thanks for your answer but is it supported in most browsers like firefox (i have checked it), chrome, ie (8,9,10) and safari? – Smile Jan 07 '14 at 05:23
2
I think it will ok for you
var base_url = window.location.origin;
var host = window.location.host;
var pathArray = window.location.pathname.split( '/' );

Haris N I
- 6,474
- 6
- 29
- 35