简体   繁体   English

如果没有顶级域名,则在不使用协议或www的情况下验证网址的字符串

[英]Validate string for url without protocol or www if top level domain exists

I am trying to validate user input strings for valid URL. 我正在尝试验证用户输入的有效URL字符串。 I am able to test for strings that either have an http(s):// or www. 我可以测试具有http(s)://或www的字符串。 Here is my code: 这是我的代码:

var urlRegEx = /((([A-Za-z]{3,9}:(?:\/\/)?)(?:[\-;:&=\+\$,\w]+@)?[A-Za-z0-9\.\-]+|(?:www\.|[\-;:&=\+\$,\w]+@)[A-Za-z0-9\.\-]+)((?:\/[\+~%\/\.\w\-]*)?\??(?:[\-\+=&;%@\.\w]*)#?(?:[\.\!\/\\\w]*))?)/g;
if(urlRegEx.test(str)){
  alert('Valid URL');
}else{
    alert('Invalid URL');
}

It works fine, even for cases like https://google.co.in/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=list%20of%20all%20top%20level%20domains 即使在https://google.co.in/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=list%20of%20all%20top%20top%20level%20域的情况下,它也能正常工作

However, it does not validate abc.com or domain-name.tld 但是,它不会验证abc.com或domain-name.tld

I would want it to work something like Whatsapp, where any string followed by a ".", followed by a top level domain, gets converted to a url but other strings don't. 我希望它能像Whatsapp一样工作,其中任何字符串后跟“。”,然后是顶级域,都可以转换为url,而其他字符串则不能。 For example, abc.com, abc.net, abc.au etc., all get converted to URLs. 例如,abc.com,abc.net,abc.au等都将转换为URL。 However, abc.anything, won't get converted to URL. 但是,abc.anything不会转换为URL。 Even this: abc.au?kgfjhg#kjhkjh=jkhkjh/kjdhkjd is identified as a URL at Whatsapp. 即使这样:abc.au?kgfjhg#kjhkjh=jkhkjh/kjdhkjd在Whatsapp也被标识为URL。

Sure, here is an example javascript regex: 当然,这是一个javascript正则表达式示例:

^[a-zA-Z]{3,9}\.(com|au|org)[^a-zA-Z]

What it does: It matches something that starts with 3 to 9 alphabet characters, then a dot ("."), and then one of several known top level domains (com|au|org) which is a list that you can expand, followed by, if anything, a non-alphabet character (so that com and com/x will be valid top level domains, but comx will not be valid). 作用:它匹配以3到9个字母字符开头的内容,然后是点(“。”),然后是几个已知顶级域(com | au | org)中的一个,可以扩展该列表,后跟一个非字母字符(如果有的话)(因此com和com / x将是有效的顶级域,但comx将无效)。

Note this is not a regex to match standard URLs. 请注意,这不是匹配标准URL的正则表达式。

Btw I used this site to write and test the regex live, maybe you'll find it useful. 顺便说一句,我用这个网站实时编写和测试了正则表达式,也许您会发现它很有用。

If you'd like more features for the regex, feel free to comment and I'll add them 如果您想使用正则表达式的更多功能,请随时发表评论,我将其添加

Enjoy! 请享用!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM