Javascript 提取 *.com
我正在寻找一个 javascript 函数/正则表达式来从 URI 中提取 *.com...(在客户端完成)
它应该适用于以下情况:
siphone.com = siphone.com
qwr.siphone.com = siphone.com
www.qwr.siphone.com = siphone.com
qw.rock.siphone.com = siphone.com
<http://www.qwr.siphone.com> = siphone.com
非常感谢!
编辑:抱歉,我错过了一个案例:
http://www.qwr.siphone.com/default.htm = siphone.com
I am looking for a javascript function/regex to extract *.com from a URI... (to be done on client side)
It should work for the following cases:
siphone.com = siphone.com
qwr.siphone.com = siphone.com
www.qwr.siphone.com = siphone.com
qw.rock.siphone.com = siphone.com
<http://www.qwr.siphone.com> = siphone.com
Much appreciated!
Edit: Sorry, I missed a case:
http://www.qwr.siphone.com/default.htm = siphone.com
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
我想这个正则表达式应该适用于少数情况:
我不擅长JavaScript,但应该有一个用于分割 URI 的库,对吗?
根据该链接,这是一个“严格”正则表达式:
如您所见,最好只使用“库”。 :)
I guess this regex should work for a few cases:
I'm not good with JavaScript, but there should be a library for splitting URIs out there, right?
According to that link, here's a "strict" regex:
As you can see, you're better off just using the "library". :)
这应该可以做到。我为一些不匹配添加了一些案例。
This should do it. I added a few cases for some nonmatches.
我已将给定的演示字符串放入 myStrings 数组中。
i - 是迭代此数组的索引。 以下行执行匹配技巧:
并返回 siphone.com 的值。如果您想匹配 .net 等 - 添加 (com|net|other) 而不是仅添加 (com)。
此外,您可能会发现以下链接很有用:正则表达式备忘单
更新:漏掉的案例也有效 %)
I've placed given demo strings to the myStrings array.
i - is index to iterate through this array. The following line does the matching trick:
and returns the value of siphone.com. If you'd like to match .net and etc. - add (com|net|other) instead of just (com).
Also you may find the following link useful: Regular expressions Cheat Sheet
update: missed case works too %)
您可以拆分字符串,然后像这样搜索
.com
字符串You could split the string then search for the
.com
string like so这假设您只需要主机名和 tld。它还假设也没有路径信息。
现在更新,您还需要使用可以执行的路径处理 uri:
This assumes that you want just the hostname and tld. It also assumes that there is no path information either.
Updated now that you also need to handle uris with paths you could do:
使用正则表达式来做到这一点。这样对检测的修改就非常容易了。
如果您使用
url.match(/(([^.]+)\.com)[^az]/i)[1]
代替。您可以确保“.com”后面没有任何其他字符。Use regexp to do that. This way modifications to the detections are quite easy.
If you use
url.match(/(([^.]+)\.com)[^a-z]/i)[1]
instead. You can assure that the ".com" is not followed by any other characters.