如何在JavaScript中从URL中提取主机?

eeq64g8w  于 2023-01-04  发布在  Java
关注(0)|答案(6)|浏览(162)

捕获域,直到结束字符$, \?, /, :。我需要一个正则表达式,捕获所有这些example.com

example.com:3000
example.com?pass=gas
example.com/
example.com
332nm8kg

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元素上可用的其他属性。

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

编辑#2

经过进一步考虑,我查看了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

编辑#1

如果你想知道如何使用jsdomnodejs解决这个问题,请查看这篇文章的修订历史

6tr1vspr

6tr1vspr2#

由于您使用的是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);
});
hlswsv35

hlswsv353#

出现了新的挑战者,根据节点文档,您还可以使用

var url = new URL(urlString);
   console.log(url.hostname);

https://nodejs.org/api/url.html#url_the_whatwg_url_api
这似乎是一种更流行的方式。

oxalkeyp

oxalkeyp4#

我使用节点^10,这就是我从URL中提取主机名的方法。

var url = URL.parse('https://stackoverflow.com/q/13506460/2535178')
console.log(url.hostname)
//=> stackoverflow.com
46scxncf

46scxncf5#

/^((?:[a-z0-9-_]+\.)*[a-z0-9-_]+\.?)(?::([0-9]+))?(.*)$/i

匹配项包括主机、端口、路径

vkc1a9a2

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)
})

相关问题