捕获域,直到结束字符$, \?, /, :。我需要一个正则表达式,捕获所有这些example.com。
$, \?, /, :
example.com
example.com:3000 example.com?pass=gas example.com/ example.com
332nm8kg1#
如果您确实拥有有效的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
注意,当您使用的语言具有其他内置方法时,使用regex来处理这种事情是愚蠢的。A元素上可用的其他属性。
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文档,发现了这个小宝石:* * 一米一米一**上面的代码可以重写为:
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解决这个问题,请查看这篇文章的修订历史
jsdom
nodejs
6tr1vspr2#
由于您使用的是node,因此只需使用内置的url.parse()方法;您希望得到的hostname属性:
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); });
hlswsv353#
出现了新的挑战者,根据节点文档,您还可以使用
var url = new URL(urlString); console.log(url.hostname);
https://nodejs.org/api/url.html#url_the_whatwg_url_api这似乎是一种更流行的方式。
oxalkeyp4#
我使用节点^10,这就是我从URL中提取主机名的方法。
^10
var url = URL.parse('https://stackoverflow.com/q/13506460/2535178') console.log(url.hostname) //=> stackoverflow.com
46scxncf5#
/^((?:[a-z0-9-_]+\.)*[a-z0-9-_]+\.?)(?::([0-9]+))?(.*)$/i
匹配项包括主机、端口、路径
vkc1a9a26#
我建议使用new URL class,它现在已经包含在大多数浏览器中。
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) })
6条答案
按热度按时间332nm8kg1#
如果您确实拥有有效的URL,这将起作用:
注意,当您使用的语言具有其他内置方法时,使用regex来处理这种事情是愚蠢的。
A
元素上可用的其他属性。编辑#2
经过进一步考虑,我查看了Node.js文档,发现了这个小宝石:* * 一米一米一**
上面的代码可以重写为:
编辑#1
如果你想知道如何使用
jsdom
和nodejs
解决这个问题,请查看这篇文章的修订历史6tr1vspr2#
由于您使用的是node,因此只需使用内置的
url.parse()
方法;您希望得到的hostname
属性:hlswsv353#
出现了新的挑战者,根据节点文档,您还可以使用
https://nodejs.org/api/url.html#url_the_whatwg_url_api
这似乎是一种更流行的方式。
oxalkeyp4#
我使用节点
^10
,这就是我从URL中提取主机名的方法。46scxncf5#
匹配项包括主机、端口、路径
vkc1a9a26#
我建议使用new URL class,它现在已经包含在大多数浏览器中。