gpt4 book ai didi

javascript - 使用 javascript 获取主机名(基本 URL)

转载 作者:行者123 更新时间:2023-11-29 10:05:12 32 4
gpt4 key购买 nike

我有太多方法可以获取主机名,如下面的代码:

window.location.host // you'll get sub.domain.com:8080 or sub.domain.com:80
window.location.hostname // you'll get sub.domain.com
window.location.protocol // you'll get http:
window.location.port // you'll get 8080 or 80
window.location.pathname // you'll get /virtualPath

就我而言,我想要一些不同的东西。例如:

我的质量检查站点名称是 example.com/testsite/index.html

我的 PROD 站点名称是 example.com/index.html

使用上述方法获取主机名的问题是它只返回主机名,如下所示:example.com

但是对于 QA,我需要返回 example.com/testsite

对于 PROD,我需要返回 example.com

是否可以使用单一代码?提前致谢。

最佳答案

要实现您的要求,您需要检查 window.location.hostname,以及 window.location.pathname 中的第一个文件夹。像这样:

function getPath() {
var folder = (window.location.pathname.split('/')[0] || '').toLowerCase() == 'testsite' ? '/testsite' : '';
return window.location.hostname + folder;
}

关于javascript - 使用 javascript 获取主机名(基本 URL),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44945153/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com