我想匹配的只是一个URL的根,而不是一个文本字符串的整个URL。考虑到:

http://www.youtube.com/watch?v=ClkQA2Lb_iE
http://youtu.be/ClkQA2Lb_iE
http://www.example.com/12xy45
http://example.com/random

我想让最后2个实例解析到www.example.com或example.com域。

我听说正则表达式很慢,这将是我在页面上的第二个正则表达式,所以如果有办法做到没有正则表达式,请告诉我。

我正在寻找这个解决方案的JS/jQuery版本。


当前回答

只需使用URL()构造函数:

new URL(url).host

其他回答

import URL from 'url';

const pathname = URL.parse(url).path;
console.log(url.replace(pathname, ''));

这样就兼顾了协议。

function hostname(url) {
    var match = url.match(/:\/\/(www[0-9]?\.)?(.[^/:]+)/i);
    if ( match != null && match.length > 2 && typeof match[2] === 'string' && match[2].length > 0 ) return match[2];
}

上面的代码将成功解析以下示例url的主机名: http://WWW.first.com/folder/page.html first.com http://mail.google.com/folder/page.html mail.google.com https://mail.google.com/folder/page.html mail.google.com http://www2.somewhere.com/folder/page.html?q=1 somewhere.com https://www.another.eu/folder/page.html?q=1 another.eu

原文出处:http://www.primaryobjects.com/CMS/Article145

代码:

var regex = /\w+.(com|co\.kr|be)/ig;
var urls = ['http://www.youtube.com/watch?v=ClkQA2Lb_iE',
            'http://youtu.be/ClkQA2Lb_iE',
            'http://www.example.com/12xy45',
            'http://example.com/random'];


$.each(urls, function(index, url) {
    var convertedUrl = url.match(regex);
    console.log(convertedUrl);
});

结果:

youtube.com
youtu.be
example.com
example.com

如果你在这个页面结束,你正在寻找最好的正则表达式的url试试这个:

^(?:https?:)?(?:\/\/)?([^\/\?]+)

https://regex101.com/r/pX5dL9/1

你可以像下面这样使用它,也可以用不区分大小写的方式来匹配HTTPS和HTTP:

const match = str.match(/^(?:https?:)?(?:\/\/)?([^\/\?]+)/i);
const hostname = match && match[1];

它适用于url没有http://,与http,与https,与只是//和不抓取路径和查询路径以及。

祝你好运

Parse-Urls似乎是具有最健壮模式的JavaScript库

以下是功能概述:

第1章。规范化或解析一个URL

第二章。提取所有url

第三章。提取具有特定名称的uri

第四章。提取所有模糊url

第五章。突出显示文本中的所有url

第六章。提取原始HTML或XML中的所有url