我想匹配的只是一个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版本。
有两个很好的解决方案,这取决于你是否需要优化性能(并且没有外部依赖!):
1. 使用URL。便于阅读的主机名
最简洁和最简单的解决方案是使用URL.hostname。
getHostname = (url) => {
//使用URL构造函数并返回主机名
返回新URL(URL).hostname;
}
/ /测试
console.log (getHostname (" https://stackoverflow.com/questions/8498592/extract-hostname-name-from-string/ "));
console.log (getHostname (" https://developer.mozilla.org/en-US/docs/Web/API/URL/hostname "));
URL。主机名是URL API的一部分,除IE (caniuse)之外的所有主流浏览器都支持。如果需要支持旧浏览器,请使用URL填充。
额外的好处:使用URL构造函数还可以让你访问其他URL属性和方法!
2. 使用RegEx来提高性能
URL。对于大多数用例,主机名应该是您的选择。然而,它仍然比这个正则表达式慢得多(你自己在jsPerf上测试):
const getHostnameFromRegex = (url) => {
//运行正则表达式
const匹配= url.match (/ ^ https ?\:\/\/([^\/?#]+)(?:[\/?#]|$)/ 我);
//提取主机名(如果没有匹配则为空)
返回匹配&&匹配[1];
}
/ /测试
console.log (getHostnameFromRegex (" https://stackoverflow.com/questions/8498592/extract-hostname-name-from-string/ "));
console.log (getHostnameFromRegex (" https://developer.mozilla.org/en-US/docs/Web/API/URL/hostname "));
博士TL;
你应该使用URL.hostname。如果您需要处理大量的url(其中性能是一个因素),请考虑RegEx。
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