4

Hi I tried to get the base URL and file path from my windows URL..But I cant get it..Please correct me..

The URL is:

http://sample.com:30023/portal/site/samples/index.jsp

The current output is: http://sample.com:30023/index.jsp?

The required output is: http://sample.com:30023/portal/site/samples/

Code used :

var baseURL = location.protocol + "//" + location.hostname + (location.port && ":" + location.port) + "/";
2
  • 1
    It appears from your code used that the current output can't possibly end with 'index.jsp'. Commented Jan 31, 2013 at 13:15
  • The safer way is to use base tag (see w3schools.com/tags/tag_base.asp) and getting in js with document.querySelector('head > base').getAttribute('href'). Commented Oct 11, 2016 at 13:02

2 Answers 2

5

add location.pathname, so it becomes

var baseURL = location.protocol + "//" + location.hostname + (location.port && ":" + location.port) + location.pathname;

Also, why not simply use location.href to get the whole thing?

Good reference at https://developer.mozilla.org/en-US/docs/DOM/window.location

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

Comments

1

Maybe somthing like this:

var sBase = location.href.substr(0, location.href.lastIndexOf("/") + 1);

3 Comments

This is the perfect answer for my question..Thank you
This is actually not a good way since it fails on a url that ends with for example "/foo/bar/baz.html?next=/login". It is better to reconstruct the URL manually to make sure the query and fragment are not included.
Addressing concern of @StefanArentz, it becomes location.origin + location.pathname.substr(0, location.pathname.lastIndexOf("/") + 1)

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.