从字符串中提取主机名称

我只想匹配一个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.comexample.com域。

我听说正则表达式很慢,这将是我在页面上的第二个正则表达式,所以如果有反正没有正则表达式让我知道。

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

尝试:

 function extractHostname(url) { var hostname; //find & remove protocol (http, ftp, etc.) and get hostname if (url.indexOf("://") > -1) { hostname = url.split('/')[2]; } else { hostname = url.split('/')[0]; } //find & remove port number hostname = hostname.split(':')[0]; //find & remove "?" hostname = hostname.split('?')[0]; return hostname; } document.write('Using "extractHostname":<br/>'); document.write(extractHostname("http://www.blog.classroom.me.uk/index.php") + "<br/>"); document.write(extractHostname("http://www.youtube.com/watch?v=ClkQA2Lb_iE") + "<br/>"); document.write(extractHostname("https://www.youtube.com/watch?v=ClkQA2Lb_iE") + "<br/>"); document.write(extractHostname("www.youtube.com/watch?v=ClkQA2Lb_iE") + "<br/>"); document.write(extractHostname("ftps://ftp.websitename.com/dir/file.txt") + "<br/>"); document.write(extractHostname("websitename.com:1234/dir/file.txt") + "<br/>"); document.write(extractHostname("ftps://websitename.com:1234/dir/file.txt") + "<br/>"); document.write(extractHostname("example.com?param=value") + "<br/>"); document.write('<br/>'); 

为了解决那些想要“根域”的人,使用这个函数:

 function extractRootDomain(url) { var domain = extractHostname(url), splitArr = domain.split('.'), arrLen = splitArr.length; //extracting the root domain here //if there is a subdomain if (arrLen > 2) { domain = splitArr[arrLen - 2] + '.' + splitArr[arrLen - 1]; //check to see if it's using a Country Code Top Level Domain (ccTLD) (ie ".me.uk") if (splitArr[arrLen - 1].length == 2 && splitArr[arrLen - 1].length == 2) { //this is using a ccTLD domain = splitArr[arrLen - 3] + '.' + domain; } } return domain; } document.write('Using "extractRootDomain":<br/>'); document.write(extractRootDomain("http://www.blog.classroom.me.uk/index.php") + "<br/>"); document.write(extractRootDomain("http://www.youtube.com/watch?v=ClkQA2Lb_iE") + "<br/>"); document.write(extractRootDomain("https://www.youtube.com/watch?v=ClkQA2Lb_iE") + "<br/>"); document.write(extractRootDomain("www.youtube.com/watch?v=ClkQA2Lb_iE") + "<br/>"); document.write(extractRootDomain("ftps://ftp.websitename.com/dir/file.txt") + "<br/>"); document.write(extractRootDomain("websitename.com:1234/dir/file.txt") + "<br/>"); document.write(extractRootDomain("ftps://websitename.com:1234/dir/file.txt") + "<br/>"); document.write(extractRootDomain("example.com?param=value") + "<br/>"); 

产量:

使用“extractHostname”:

 www.blog.classroom.me.uk www.youtube.com www.youtube.com www.youtube.com ftp.websitename.com websitename.com websitename.com example.com 

使用“extractRootDomain”:

 classroom.me.uk youtube.com youtube.com youtube.com websitename.com websitename.com websitename.com example.com 

不管有协议还是端口号,都可以提取域名。 这是一个非常简单的,非正则表达式的解决方案,所以我认为这样做。

注意:如果您尝试在没有协议的输入上使用“URL”对象(例如http,ftp等),它将会中断。

*谢谢@Timmerz,@renoirb,@rineez,@BigDong,@ ra00l,@ILikeBeansTacos,@CharlesRobertson为您的建议!

没有使用正则表达式的巧妙技巧:

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

尝试这个:

 var matches = url.match(/^https?\:\/\/([^\/?#]+)(?:[\/?#]|$)/i); var domain = matches && matches[1]; // domain will be null if no match is found 

如果要从结果中排除端口,请改用此表达式:

 /^https?\:\/\/([^\/:?#]+)(?:[\/:?#]|$)/i 

编辑:为了防止特定的域匹配,使用负向前视。 (?!youtube.com)

 /^https?\:\/\/(?!(?:www\.)?(?:youtube\.com|youtu\.be))([^\/:?#]+)(?:[\/:?#]|$)/i 

解析URL可能会非常棘手,因为您可以使用端口号和特殊字符。 因此,我建议使用像parseUri这样的东西来为你做这个。 除非你解析了数百个URL,否则我怀疑性能会成为一个问题。

没有必要解析字符串,只需将URL作为参数传递给URL构造函数 :

 var url = 'http://www.youtube.com/watch?v=ClkQA2Lb_iE'; var hostname = (new URL(url)).hostname; assert(hostname === 'www.youtube.com'); 

我试图使用给定的解决方案,选择一个是为了我的目的矫枉过正和“创造一个元素”为我搞砸了。

它尚未准备好在URL中的端口。 我希望有人觉得它有用

 function parseURL(url){ parsed_url = {} if ( url == null || url.length == 0 ) return parsed_url; protocol_i = url.indexOf('://'); parsed_url.protocol = url.substr(0,protocol_i); remaining_url = url.substr(protocol_i + 3, url.length); domain_i = remaining_url.indexOf('/'); domain_i = domain_i == -1 ? remaining_url.length - 1 : domain_i; parsed_url.domain = remaining_url.substr(0, domain_i); parsed_url.path = domain_i == -1 || domain_i + 1 == remaining_url.length ? null : remaining_url.substr(domain_i + 1, remaining_url.length); domain_parts = parsed_url.domain.split('.'); switch ( domain_parts.length ){ case 2: parsed_url.subdomain = null; parsed_url.host = domain_parts[0]; parsed_url.tld = domain_parts[1]; break; case 3: parsed_url.subdomain = domain_parts[0]; parsed_url.host = domain_parts[1]; parsed_url.tld = domain_parts[2]; break; case 4: parsed_url.subdomain = domain_parts[0]; parsed_url.host = domain_parts[1]; parsed_url.tld = domain_parts[2] + '.' + domain_parts[3]; break; } parsed_url.parent_domain = parsed_url.host + '.' + parsed_url.tld; return parsed_url; } 

运行这个:

 parseURL('https://www.facebook.com/100003379429021_356001651189146'); 

结果:

 Object { domain : "www.facebook.com", host : "facebook", path : "100003379429021_356001651189146", protocol : "https", subdomain : "www", tld : "com" } 

如果你最终在这个页面上,你正在寻找最好的URL的REGEX尝试这一个:

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

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

它适用于不使用http://的url,使用http,使用https,仅使用//并且不抓取路径和查询路径。

祝你好运

 // use this if you know you have a subdomain // www.domain.com -> domain.com function getDomain() { return window.location.hostname.replace(/([a-zA-Z0-9]+.)/,""); } 
 String.prototype.trim = function(){return his.replace(/^\s+|\s+$/g,"");} function getHost(url){ if("undefined"==typeof(url)||null==url) return ""; url = url.trim(); if(""==url) return ""; var _host,_arr; if(-1<url.indexOf("://")){ _arr = url.split('://'); if(-1<_arr[0].indexOf("/")||-1<_arr[0].indexOf(".")||-1<_arr[0].indexOf("\?")||-1<_arr[0].indexOf("\&")){ _arr[0] = _arr[0].trim(); if(0==_arr[0].indexOf("//")) _host = _arr[0].split("//")[1].split("/")[0].trim().split("\?")[0].split("\&")[0]; else return ""; } else{ _arr[1] = _arr[1].trim(); _host = _arr[1].split("/")[0].trim().split("\?")[0].split("\&")[0]; } } else{ if(0==url.indexOf("//")) _host = url.split("//")[1].split("/")[0].trim().split("\?")[0].split("\&")[0]; else return ""; } return _host; } function getHostname(url){ if("undefined"==typeof(url)||null==url) return ""; url = url.trim(); if(""==url) return ""; return getHost(url).split(':')[0]; } function getDomain(url){ if("undefined"==typeof(url)||null==url) return ""; url = url.trim(); if(""==url) return ""; return getHostname(url).replace(/([a-zA-Z0-9]+.)/,""); } 
 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

好吧,我知道这是一个老问题,但我做了一个超高效的url解析器,所以我想我会分享它。

正如你所看到的,这个函数的结构很奇怪,但这是为了提高效率。 没有原型函数被使用,字符串不会被迭代超过一次,也没有任何字符被处理超过需要。

 function getDomain(url) { var dom = "", v, step = 0; for(var i=0,l=url.length; i<l; i++) { v = url[i]; if(step == 0) { //First, skip 0 to 5 characters ending in ':' (ex: 'https://') if(i > 5) { i=-1; step=1; } else if(v == ':') { i+=2; step=1; } } else if(step == 1) { //Skip 0 or 4 characters 'www.' //(Note: Doesn't work with www.com, but that domain isn't claimed anyway.) if(v == 'w' && url[i+1] == 'w' && url[i+2] == 'w' && url[i+3] == '.') i+=4; dom+=url[i]; step=2; } else if(step == 2) { //Stop at subpages, queries, and hashes. if(v == '/' || v == '?' || v == '#') break; dom += v; } } return dom; } 

这里是jQuery单线程:

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

简而言之,你可以这样做

 var url = "http://www.someurl.com/support/feature" function getDomain(url){ domain=url.split("//")[1]; return domain.split("/")[0]; } eg: getDomain("http://www.example.com/page/1") output: "www.example.com" 

使用上述功能获取域名

正在寻找解决这个问题的今天。 上述答案似乎没有一个满足。 我想要一个解决方案,可以是一个班轮,没有条件逻辑,什么都不必包装在一个函数。

这就是我想到的,似乎工作得很好:

主机名= “http://www.example.com:1234”
 hostname.split(“//”)。slice(-1)[0] .split(“:”)[0] .split('。')。slice(-2).join('。')//给“example.com”

乍一看可能看起来很复杂,但是工作很简单; 关键是在几个地方使用'slice(-n)',其中好的部分必须从分割数组的末端 (和[0]从分割数组的前部得到)拉出。

每个测试返回“example.com”:

 “http://example.com” .split( “//”).slice(-1)[0] .split( “:”)。[0] .split( '')切片(-2)。加入('。')
 “http://example.com:1234".split("//").slice(-1)[0].split(":")[0].split('.').slice(-2 )。加入('。')
 “http://www.example.com:1234” .split( “//”).slice(-1)[0] .split( “:”)。[0] .split( '')切片( -2)。加入( '')
 “http://foo.www.example.com:1234” .split( “//”).slice(-1)[0] .split( “:”)[0] .split( '')。切片(-2)。加入( '')

这不是一个完整的答案,但下面的代码应该可以帮助你:

 function myFunction() { var str = "https://www.123rf.com/photo_10965738_lots-oop.html"; matches = str.split('/'); return matches[2]; } 

我希望有人比我更快创建代码。 这也有助于改善我自己。

所有的url属性,没有依赖关系,没有JQuery,容易理解

这个解决方案给你的答案加上其他属性。 不需要JQuery或其他依赖项,粘贴并去。

用法

 getUrlParts("https://news.google.com/news/headlines/technology.html?ned=us&hl=en") 

产量

 { "origin": "https://news.google.com", "domain": "news.google.com", "subdomain": "news", "domainroot": "google.com", "domainpath": "news.google.com/news/headlines", "tld": ".com", "path": "news/headlines/technology.html", "query": "ned=us&hl=en", "protocol": "https", "port": 443, "parts": [ "news", "google", "com" ], "segments": [ "news", "headlines", "technology.html" ], "params": [ { "key": "ned", "val": "us" }, { "key": "hl", "val": "en" } ] } 


代码被设计为易于理解而不是超级快速。 它每秒钟可以轻松调用100次,所以对于前端或者少量的服务器使用来说非常好,但是对于大容量的吞吐量来说却不是。

 function getUrlParts(fullyQualifiedUrl) { var url = {}, tempProtocol var a = document.createElement('a') // if doesn't start with something like https:// it's not a url, but try to work around that if (fullyQualifiedUrl.indexOf('://') == -1) { tempProtocol = 'https://' a.href = tempProtocol + fullyQualifiedUrl } else a.href = fullyQualifiedUrl var parts = a.hostname.split('.') url.origin = tempProtocol ? "" : a.origin url.domain = a.hostname url.subdomain = parts[0] url.domainroot = '' url.domainpath = '' url.tld = '.' + parts[parts.length - 1] url.path = a.pathname.substring(1) url.query = a.search.substr(1) url.protocol = tempProtocol ? "" : a.protocol.substr(0, a.protocol.length - 1) url.port = tempProtocol ? "" : a.port ? a.port : a.protocol === 'http:' ? 80 : a.protocol === 'https:' ? 443 : a.port url.parts = parts url.segments = a.pathname === '/' ? [] : a.pathname.split('/').slice(1) url.params = url.query === '' ? [] : url.query.split('&') for (var j = 0; j < url.params.length; j++) { var param = url.params[j]; var keyval = param.split('=') url.params[j] = { 'key': keyval[0], 'val': keyval[1] } } // domainroot if (parts.length > 2) { url.domainroot = parts[parts.length - 2] + '.' + parts[parts.length - 1]; // check for country code top level domain if (parts[parts.length - 1].length == 2 && parts[parts.length - 1].length == 2) url.domainroot = parts[parts.length - 3] + '.' + url.domainroot; } // domainpath (domain+path without filenames) if (url.segments.length > 0) { var lastSegment = url.segments[url.segments.length - 1] var endsWithFile = lastSegment.indexOf('.') != -1 if (endsWithFile) { var fileSegment = url.path.indexOf(lastSegment) var pathNoFile = url.path.substr(0, fileSegment - 1) url.domainpath = url.domain if (pathNoFile) url.domainpath = url.domainpath + '/' + pathNoFile } else url.domainpath = url.domain + '/' + url.path } else url.domainpath = url.domain return url } 

码:

 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 

尝试下面的代码使用正则表达式确切的域名,

String line =“ http://www.youtube.com/watch?v=ClkQA2Lb_iE ”;

  String pattern3="([\\w\\W]\\.)+(.*)?(\\.[\\w]+)"; Pattern r = Pattern.compile(pattern3); Matcher m = r.matcher(line); if (m.find( )) { System.out.println("Found value: " + m.group(2) ); } else { System.out.println("NO MATCH"); }