如何从JavaScript中的URL中提取主机? [英] How to extract the host from a URL in JavaScript?

查看:91
本文介绍了如何从JavaScript中的URL中提取主机?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Capture the domain till the ending characters $, \?, /, :. I need a regex that captures domian.com in all of these.

domain.com:3000
domain.com?pass=gas
domain.com/
domain.com


推荐答案

如果您确实拥有有效的网址,这将有效:

If you actually have valid URLs, this will work:

var urls = [
    'http://domain.com:3000',
    'http://domain.com?pass=gas',
    'http://domain.com/',
    'http://domain.com'
];

for (x in urls) {
    var a = document.createElement('a');
    a.href = urls[x];
    console.log(a.hostname);
}

//=> domain.com
//=> domain.com
//=> domain.com
//=> domain.com

注意,当你使用的语言使用正则表达式时,这种事情很愚蠢有其他内置方法。

Note, using regex for this kind of thing is silly when the language you're using has other built-in methods.

A 元素可用的其他属性。

Other properties available on A elements.

var a = document.createElement('a');
a.href = "http://domain.com:3000/path/to/something?query=string#fragment"

a.protocol   //=> http:
a.hostname   //=> domain.com
a.port       //=> 3000
a.pathname   //=> /path/to/something
a.search     //=> ?query=string
a.hash       //=> #fragment
a.host       //=> domain.com:3000






编辑#2



经过进一步的考虑,我查看了Node.js文档并找到了这个小宝石: url #parse

上面的代码可以改写为:

The code above can be rewritten as:

var url = require('url');

var urls = [
    'http://domain.com:3000',
    'http://domain.com?pass=gas',
    'http://domain.com/',
    'http://domain.com'
];

for (x in urls) {
    console.log(url.parse(urls[x]).hostname);
}

//=> domain.com
//=> domain.com
//=> domain.com
//=> domain.com






编辑#1



如果您想了解如何使用 jsdom 和<$ c $来解决此问题,请参阅此帖子的修订历史记录c> nodejs

这篇关于如何从JavaScript中的URL中提取主机?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆