Javascript 从 URL 获取协议、域和端口
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6941533/
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
Get protocol, domain, and port from URL
提问by yelo3
I need to extract the full protocol, domain, and port from a given URL. For example:
我需要从给定的 URL 中提取完整的协议、域和端口。例如:
https://localhost:8181/ContactUs-1.0/contact?lang=it&report_type=consumer
>>>
https://localhost:8181
采纳答案by wezzy
first get the current address
首先获取当前地址
var url = window.location.href
Then just parse that string
然后只需解析该字符串
var arr = url.split("/");
your url is:
你的网址是:
var result = arr[0] + "//" + arr[2]
Hope this helps
希望这可以帮助
回答by Shef
var full = location.protocol+'//'+location.hostname+(location.port ? ':'+location.port: '');
回答by David Calhoun
None of these answers seem to completely address the question, which calls for an arbitrary url, not specifically the url of the current page.
这些答案似乎都没有完全解决这个问题,它需要一个任意的 url,而不是当前页面的 url。
Method 1: Use the URL API (caveat: no IE11 support)
方法 1:使用 URL API(警告:不支持 IE11)
You can use the URL API(not supported by IE11, but available everywhere else).
您可以使用URL API(IE11 不支持,但在其他任何地方都可用)。
This also makes it easy to access search params. Another bonus: it can be used in a Web Worker since it doesn't depend on the DOM.
这也使访问搜索参数变得容易。另一个好处:它可以在 Web Worker 中使用,因为它不依赖于 DOM。
const url = new URL('http://example.com:12345/blog/foo/bar?startIndex=1&pageSize=10');
Method 2 (old way): Use the browser's built-in parser in the DOM
方法 2(旧方法):在 DOM 中使用浏览器内置的解析器
Use this if you need this to work on older browsers as well.
如果您也需要在旧浏览器上使用它,请使用它。
// Create an anchor element (note: no need to append this element to the document)
const url = document.createElement('a');
// Set href to any path
url.setAttribute('href', 'http://example.com:12345/blog/foo/bar?startIndex=1&pageSize=10');
That's it!
就是这样!
The browser's built-in parser has already done its job. Now you can just grab the parts you need (note that this works for both methods above):
浏览器的内置解析器已经完成了它的工作。现在您可以只获取您需要的部分(请注意,这适用于上述两种方法):
// Get any piece of the url you're interested in
url.hostname; // 'example.com'
url.port; // 12345
url.search; // '?startIndex=1&pageSize=10'
url.pathname; // '/blog/foo/bar'
url.protocol; // 'http:'
Bonus: Search params
奖励:搜索参数
Chances are you'll probably want to break apart the search url params as well, since '?startIndex=1&pageSize=10' isn't too useable on its own.
您可能还想拆分搜索 url 参数,因为 '?startIndex=1&pageSize=10' 本身不太可用。
If you used Method 1 (URL API) above, you simply use the searchParams getters:
如果您使用了上面的方法 1(URL API),您只需使用 searchParams 获取器:
url.searchParams.get('startIndex'); // '1'
Or to get all parameters:
或者获取所有参数:
Array
.from(url.searchParams)
.reduce((accum, [key, val]) => {
accum[key] = val;
return accum;
}, {});
// -> { startIndex: '1', pageSize: '10' }
If you used Method 2 (the old way), you can use something like this:
如果您使用了方法 2(旧方法),则可以使用以下方法:
// Simple object output (note: does NOT preserve duplicate keys).
var params = url.search.substr(1); // remove '?' prefix
params
.split('&')
.reduce((accum, keyval) => {
const [key, val] = keyval.split('=');
accum[key] = val;
return accum;
}, {});
// -> { startIndex: '1', pageSize: '10' }
回答by Pijusn
For some reason all the answers are all overkills. This is all it takes:
出于某种原因,所有的答案都是矫枉过正。这就是全部:
window.location.origin
More details can be found here: https://developer.mozilla.org/en-US/docs/Web/API/window.location#Properties
更多细节可以在这里找到:https: //developer.mozilla.org/en-US/docs/Web/API/window.location#Properties
回答by Toby
As has already been mentioned there is the as yet not fully supported window.location.origin
but instead of either using it or creating a new variable to use, I prefer to check for it and if it isn't set to set it.
正如已经提到的,目前还没有完全支持,window.location.origin
但不是使用它或创建一个新变量来使用,我更喜欢检查它,如果它没有设置为设置它。
For example;
例如;
if (!window.location.origin) {
window.location.origin = window.location.protocol + "//" + window.location.hostname + (window.location.port ? ':' + window.location.port: '');
}
I actually wrote about this a few months back A fix for window.location.origin
我实际上在几个月前写过这个问题 修复 window.location.origin
回答by Miroslav Holec
host
主持人
var url = window.location.host;
returns localhost:2679
返回 localhost:2679
hostname
主机名
var url = window.location.hostname;
returns localhost
返回 localhost
回答by int soumen
window.location.origin
will be enough to get the same.
window.location.origin
将足以得到相同的。
回答by Дамян Станчев
The protocol property sets or returns the protocol of the current URL, including the colon (:).
protocol 属性设置或返回当前 URL 的协议,包括冒号 (:)。
This means that if you want to get only the HTTP/HTTPS part you can do something like this:
这意味着如果您只想获得 HTTP/HTTPS 部分,您可以执行以下操作:
var protocol = window.location.protocol.replace(/:/g,'')
For the domain you can use:
对于域,您可以使用:
var domain = window.location.hostname;
For the port you can use:
对于端口,您可以使用:
var port = window.location.port;
Keep in mind that the port will be an empty string if it is not visible in the URL. For example:
请记住,如果该端口在 URL 中不可见,则该端口将是一个空字符串。例如:
- http://example.com/will return "" for port
- http://example.com:80/will return 80 for port
- http://example.com/将返回“”作为端口
- http://example.com:80/将返回 80 端口
If you need to show 80/443 when you have no port use
如果在没有端口使用的情况下需要显示80/443
var port = window.location.port || (protocol === 'https' ? '443' : '80');
回答by cpu
Indeed, window.location.originworks fine in browsers following standards, but guess what. IE isn't following standards.
实际上,window.location.origin在遵循标准的浏览器中运行良好,但你猜怎么着。IE 不遵循标准。
So because of that, this is what worked for me in IE, FireFox and Chrome:
因此,这就是我在 IE、FireFox 和 Chrome 中工作的方法:
var full = location.protocol+'//'+location.hostname+(location.port ? ':'+location.port: '');
but for possible future enhancements which could cause conflicts, I specified the "window" reference before the "location" object.
但是对于可能导致冲突的未来增强功能,我在“位置”对象之前指定了“窗口”引用。
var full = window.location.protocol+'//'+window.location.hostname+(window.location.port ? ':'+window.location.port: '');
回答by Maik de Kruif
Why not use:
为什么不使用:
let full = window.location.origin