3

I am trying to extract the base of the url:

http://google.com/something --> http://google.com
http://127.0.0.1:8000/something --> http://127.0.0.1:8000

When I try and use the following:

var pathArray = window.location.pathname;
alert(pathArray);

I get pathArray = undefined. Note: using location.hostname does work here. Why is .pathname returning undefined, and how would I get the url base here? Thank you.

Update: I used var pathArray = 'http://' + window.location.

1
  • 1
    Path name does not return the domain name. It returns the pat after the domain name. If you're at http://example.com/a/b.html, window.location.pathname returns /a/b.html. Why not use window.location? Commented Sep 19, 2011 at 22:11

2 Answers 2

5

https://developer.mozilla.org/en-US/docs/Web/API/Window/location May not work in all browsers, as per usual

I'd just get window.location and parse it.

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

Comments

-1

Try window.location.host, it works for http://localhost:8000, so it should work for your case

4 Comments

window.location.host won't return the port number, nor the protocol.
It does. Testing it in Firefox with Firebug
On Chrome and Firefox on localhost/index.html, using console.log(window.location.host); I get localhost returned.
Yes, because it doesnt have port number. Even the solution which you suggested doesnt work for localhost/index.html example. i.e(window.location.protocol + '//' + window.location.host;). If you want port number for mapped URL in host entries, then you have to explicitly give window.location.port

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.