How to get the base path in jQuery?

送分小仙女□ 提交于 2019-12-20 10:17:58

问题


window.locationworks 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?


回答1:


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.




回答2:


You can use this statement

var baseUrl = document.location.origin;



回答3:


Try this:

location.protocol + "//" + location.host



回答4:


I think it will ok for you

var base_url = window.location.origin;

var host = window.location.host;

var pathArray = window.location.pathname.split( '/' );


来源:https://stackoverflow.com/questions/17992578/how-to-get-the-base-path-in-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!