捕获域名,直到结束字符
$, \?, /, :
。我需要一个正则表达式来在这些情况下都捕获example.com
。example.com:3000
example.com?pass=gas
example.com/
example.com
$, \?, /, :
。我需要一个正则表达式来在这些情况下都捕获example.com
。example.com:3000
example.com?pass=gas
example.com/
example.com
如果您实际上拥有有效的URL,这将有效:
var urls = [
'http://example.com:3000',
'http://example.com?pass=gas',
'http://example.com/',
'http://example.com'
];
for (x in urls) {
var a = document.createElement('a');
a.href = urls[x];
console.log(a.hostname);
}
//=> example.com
//=> example.com
//=> example.com
//=> example.com
注意,当你使用的语言有其他内置方法时,为这种事情使用正则表达式是愚蠢的。
A
元素上可用的其他属性。
var a = document.createElement('a');
a.href = "http://example.com:3000/path/to/something?query=string#fragment"
a.protocol //=> http:
a.hostname //=> example.com
a.port //=> 3000
a.pathname //=> /path/to/something
a.search //=> ?query=string
a.hash //=> #fragment
a.host //=> example.com:3000
经过进一步考虑,我查阅了Node.js文档,并找到了这个小宝石:url#parse
上面的代码可以改写为:
var url = require('url');
var urls = [
'http://example.com:3000',
'http://example.com?pass=gas',
'http://example.com/',
'http://example.com'
];
for (x in urls) {
console.log(url.parse(urls[x]).hostname);
}
//=> example.com
//=> example.com
//=> example.com
//=> example.com
如果您想了解如何使用jsdom
和nodejs
解决此问题,请查看此帖子的修订历史记录
url#parse
方法。请参见上面的编辑#2。 - maček由于您正在使用Node,只需使用内置的 url.parse()
方法即可;您需要的是返回的 hostname
属性:
var url=require('url');
var urls = [
'http://example.com:3000',
'http://example.com?pass=gas',
'http://example.com/',
'http://example.com'
];
urls.forEach(function(x) {
console.log(url.parse(x).hostname);
});
{ pathname: '0', path: '0', href: '0' } { pathname: '1', path: '1', href: '1' } { pathname: '2', path: '2', href: '2' } { pathname: '3', path: '3', href: '3' }
- ThomasReggifor (...in...)
来遍历数组。 - ebohlman var url = new URL(urlString);
console.log(url.hostname);
https://nodejs.org/api/url.html#url_the_whatwg_url_api
这似乎是一种更现代的方式。
我正在使用Node ^10
,以下是我从URL中提取主机名的方法。
var url = URL.parse('https://dev59.com/c2Yr5IYBdhLWcg3wpbyQ')
console.log(url.hostname)
//=> stackoverflow.com
我建议使用现在大多数浏览器都包含的新 URL 类。
var urls = [
'http://example.com:3000',
'http://example.com?pass=gas',
'http://example.com/',
'http://example.com'
];
urls.forEach(url => {
const u = new URL(url)
console.log(u.hostname)
})
/^((?:[a-z0-9-_]+\.)*[a-z0-9-_]+\.?)(?::([0-9]+))?(.*)$/i
匹配项包括主机、端口和路径。
"stackoverflow.com/questions/13506460/how-to-extract...".match(/^((?:[a-z0-9-]+\.)*[a-z0-9-]+\.?)(?::([0-9]+))?(.*)$/i)
完美地工作,结果为 ["stackoverflow.com/questions/13506460/how-to-extract...", "stackoverflow.com", undefined, "/questions/13506460/how-to-extract..."]
。 - stroncium/^(?:https?:\/\/)?((?:[a-z0-9-_]+\.)*[a-z0-9-_]+\.?)(?::([0-9]+))?(.*)$/i
(仅适用于http和https或根本没有URI方案)。Fiddle在这里:http://jsfiddle.net/WLGmv/1/ - stroncium