jQuery 如何在jQuery中获取基本路径?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17992578/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 20:20:24  来源:igfitidea点击:

How to get the base path in jQuery?

jqueryurlpathlocationhref

提问by leymannx

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?

window.location工作正常,但会返回完整的绝对路径,例如http://domain.xyz/punch/lines. 但我只需要http://domain.xyz/. 我怎样才能只提取第一部分?我怎样才能使它动态化,我的意思是即使子目录路径变长也始终相同?

回答by adeneo

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.pathnamewould contain the path.

作为旁注,window.location.pathname将包含路径。

回答by Peter T.

You can use this statement

您可以使用此语句

var baseUrl = document.location.origin;

回答by Dharmesh Patel

Try this:

尝试这个:

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

回答by Haris

I think it will ok for you

我想这对你没问题

var base_url = window.location.origin;

var host = window.location.host;

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