如何解析URL? [英] How to parse a URL?
问题描述
如果有一件事我无法理解,那就是正则表达式。
If there is one thing I just cant get my head around, it's regex.
所以经过大量的搜索后我终于发现了一个适合我需要的:
So after a lot of searching I finally found this one that suits my needs:
function get_domain_name()
{
aaaa="http://www.somesite.se/blah/sdgsdgsdgs";
//aaaa="http://somesite.se/blah/sese";
domain_name_parts = aaaa.match(/:\/\/(.[^/]+)/)[1].split('.');
if(domain_name_parts.length >= 3){
domain_name_parts[0] = '';
}
var domain = domain_name_parts.join('.');
if(domain.indexOf('.') == 0)
alert("1"+ domain.substr(1));
else
alert("2"+ domain);
}
它基本上让我回到了域名,无论如何我还能得到域名之后的所有东西?在这种情况下, aaaa
变量中的 / blah / sdgsdgsdgs
。
It basically gives me back the domain name, is there anyway I can also get all the stuff after the domain name? in this case it would be /blah/sdgsdgsdgs
from the aaaa
variable.
推荐答案
请注意,这个解决方案不是最好的。我这样做只是为了满足OP的要求。我个人建议查看其他答案。
以下正则表达式将为您提供域名和其他答案。 :\ / \ /(.[^ \ /] +)(.*)
:
THe following regexp will give you back the domain and the rest. :\/\/(.[^\/]+)(.*)
:
- www.google.com
- / goosomething
我建议您在此处学习RegExp文档: http://www.regular-expressions.info/reference.html
I suggest you studying the RegExp documentation here: http://www.regular-expressions.info/reference.html
使用你的函数:
function get_domain_name()
{
aaaa="http://www.somesite.se/blah/sdgsdgsdgs";
//aaaa="http://somesite.se/blah/sese";
var matches = aaaa.match(/:\/\/(?:www\.)?(.[^/]+)(.*)/);
alert(matches[1]);
alert(matches[2]);
}
这篇关于如何解析URL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!