// will return the host name and port
var host = window.location.host;
或可能
var host = window.location.protocol + "//" + window.location.host;
或者如果你喜欢串联
var protocol = location.protocol;
var slashes = protocol.concat("//");
var host = slashes.concat(window.location.host);
// or as you probably should do
var host = location.protocol.concat("//").concat(window.location.host);
// the above is the same as origin, e.g. "https://stackoverflow.com"
var host = window.location.origin;
根据您的需要,您可以使用window.location属性之一。
在你的问题中,你问的是宿主,它可以使用window.location.hostname(例如www.example.com)检索。在你的例子中,你显示的东西被称为起源,它可以使用window.location.origin(例如http://www.example.com)检索。< / p >
var path = window.location.origin + "/";
//result = "http://localhost:60470/"
1. Get the full URL:
window.location
2. Get the only protocol:
window.location.protocol
3. Get the host:
window.location.host
4. Get the host and protocol:
window.location.origin
5. Get pathname or directory without protocol and host:
var url = 'http://www.example.com/somepath/path2/path3/path4';
var pathname = new URL(url).pathname;
alert(pathname);