Javascript 没有 http、https、ftp 的 url 的正则表达式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4275525/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 11:41:08  来源:igfitidea点击:

Regex for urls without http, https, ftp

javascriptregex

提问by Guest

I'm looking for a regex that accept urls like these:

我正在寻找一个接受这样的网址的正则表达式:

http://www.example.com
www.example.com

This is what I have so far, but it regex doesn't match URLs without http://or https://, or ftp://:

到目前为止,这是我所拥有的,但它的正则表达式不匹配没有http://or 的URL https://,或者ftp://

regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;

How can I make the protocol optional?

我怎样才能使协议成为可选的?

采纳答案by Bart Kiers

Make the (ftp|http|https):\/\/part optional:

使(ftp|http|https):\/\/部件可选:

((ftp|http|https):\/\/)?

回答by Rajiv Aggarwal

Try this this will validate url with (http,ftp,https) or without(http,ftp,https)..

试试这个,这将使用 (http,ftp,https) 或不使用 (http,ftp,https) 验证 url。

/^(?:(ftp|http|https):\/\/)?(?:[\w-]+\.)+[a-z]{3,6}$/;

回答by udaykrishna

Try this this will validate url with or without(http,ftp,https) in upper and lower cases and also allows you to for numerics

试试这个,这将在大写和小写中使用或不使用(http,ftp,https)验证 url,并且还允许您使用数字

/^(?:(ftp|http|https)?:\/\/)?(?:[\w-]+\.)+([a-z]|[A-Z]|[0-9]){2,6}$/gi;

回答by udaykrishna

Kindly see https://codegolf.stackexchange.com/a/480/6593

请参阅https://codegolf.stackexchange.com/a/480/6593

Quoting from the above link:

引用上面的链接:

value = 'www.google.com';
if(/(^|\s)((https?:\/\/)?[\w-]+(\.[\w-]+)+\.?(:\d+)?(\/\S*)?)/gi.test(value)) {
            return true;
        } else {
            return false;
        }