有没有一个简单的方法可以从一个完整的URL开始:
document.location.href = "http://aaa.bbb.ccc.com/asdf/asdf/sadf.aspx?blah"
只提取主部分:
aaa.bbb.ccc.com
肯定有JavaScript函数能可靠地做到这一点,但我找不到。
有没有一个简单的方法可以从一个完整的URL开始:
document.location.href = "http://aaa.bbb.ccc.com/asdf/asdf/sadf.aspx?blah"
只提取主部分:
aaa.bbb.ccc.com
肯定有JavaScript函数能可靠地做到这一点,但我找不到。
当前回答
use
window.location.origin
对于:“http://aaa.bbb.ccc.ddd.com/sadf.aspx?blah”
你会得到:http://aaa.bbb.ccc.ddd.com/
其他回答
use
window.location.origin
对于:“http://aaa.bbb.ccc.ddd.com/sadf.aspx?blah”
你会得到:http://aaa.bbb.ccc.ddd.com/
有两种方法。第一个答案是另一个答案的变体,但这个答案说明了非默认端口:
function getRootUrl() {
var defaultPorts = {"http:":80,"https:":443};
return window.location.protocol + "//" + window.location.hostname
+ (((window.location.port)
&& (window.location.port != defaultPorts[window.location.protocol]))
? (":"+window.location.port) : "");
}
但我更喜欢这个更简单的方法(适用于任何URI字符串):
function getRootUrl(url) {
return url.toString().replace(/^(.*\/\/[^\/?#]*).*$/,"$1");
}
Regex提供了更大的灵活性。
//document.location.href = "http://aaa.bbb.ccc.com/asdf/asdf/sadf.aspx?blah
//1.
var r = new RegExp(/http:\/\/[^/]+/);
var match = r.exec(document.location.href) //gives http://aaa.bbb.ccc.com
//2.
var r = new RegExp(/http:\/\/[^/]+\/[^/]+/);
var match = r.exec(document.location.href) //gives http://aaa.bbb.ccc.com/asdf
您可以使用/来分割URL字符串
const exampleURL = “Https://exampleurl.com/page1/etc/etc” const URLsplit = exampleURL.split(“/”) console.log(网址拆分) console.log(URLsplit[2])
结果。exampleurl.com
Try
document.location.host
or
document.location.hostname