最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - get the base URL and file path from my windows URL by using Javascript - Stack Overflow

programmeradmin0浏览0评论

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:

:30023/portal/site/samples/index.jsp

The current output is: :30023/index.jsp?

The required output is: :30023/portal/site/samples/

Code used :

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

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.:30023/portal/site/samples/index.jsp

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

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

Code used :

var baseURL = location.protocol + "//" + location.hostname + (location.port && ":" + location.port) + "/";
Share Improve this question edited Jun 20, 2020 at 9:12 CommunityBot 11 silver badge asked Jan 31, 2013 at 13:08 NajuNaju 1,5417 gold badges28 silver badges60 bronze badges 2
  • 1 It appears from your code used that the current output can't possibly end with 'index.jsp'. – Peter Herdenborg Commented Jan 31, 2013 at 13:15
  • The safer way is to use base tag (see w3schools./tags/tag_base.asp) and getting in js with document.querySelector('head > base').getAttribute('href'). – Jerome2606 Commented Oct 11, 2016 at 13:02
Add a ment  | 

2 Answers 2

Reset to default 5

add location.pathname, so it bees

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/en-US/docs/DOM/window.location

Maybe somthing like this:

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

评论列表(0)

  1. 暂无评论