我想匹配的只是一个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版本。


当前回答

好吧,使用正则表达式会容易得多:

    mainUrl = "http://www.mywebsite.com/mypath/to/folder";
    urlParts = /^(?:\w+\:\/\/)?([^\/]+)(.*)$/.exec(mainUrl);
    host = Fragment[1]; // www.mywebsite.com

其他回答

一个不用正则表达式的小技巧:

var tmp        = document.createElement ('a');
;   tmp.href   = "http://www.example.com/12xy45";

// tmp.hostname will now contain 'www.example.com'
// tmp.host will now contain hostname and port 'www.example.com:80'

将上述内容包装在如下函数中,您就拥有了从URI中获取域部分的绝佳方法。

function url_domain(data) {
  var    a      = document.createElement('a');
         a.href = data;
  return a.hostname;
}

解析URL可能很棘手,因为您可以使用端口号和特殊字符。因此,我建议使用parseUri之类的东西来做这个。我怀疑性能不会成为问题,除非您要解析数百个url。

有两个很好的解决方案,这取决于你是否需要优化性能(并且没有外部依赖!):

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 myFunction() {
    var str = "https://www.123rf.com/photo_10965738_lots-oop.html";
    matches = str.split('/');
    return matches[2];
}

我想有人比我更快地创建代码。它也有助于提高我自己。

jquery Oneline

$('<a>').attr('href', document.location.href).prop('hostname');