最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Regex for urls without http, https, ftp - Stack Overflow

programmeradmin6浏览0评论

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


www.example

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

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

How can I make the protocol optional?

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://:

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

How can I make the protocol optional?

Share Improve this question edited Apr 22, 2015 at 12:40 anon asked Nov 25, 2010 at 9:34 GuestGuest 2172 gold badges3 silver badges7 bronze badges 5
  • 1 example.pl: A website in Poland or a Perl script? – Boldewyn Commented Nov 25, 2010 at 9:44
  • In the OP's case unfortunately not. It will either be consumed by the regex or not. RFC 3986 (the link leads to a regexp to parse URLs) has its reasons to enforce either a scheme or the `\` part. Although I understand the need to find such stuff (see the Linkification addon for FF) – Boldewyn Commented Nov 25, 2010 at 9:55
  • Also see stackoverflow.com/questions/4252778/… for a very generic solution. – martineno Commented Nov 25, 2010 at 10:04
  • What is a good regular expression to match a URL? – Rajat Verma Commented Sep 7, 2021 at 11:40
  • stackoverflow.com/questions/3809401/… – Rajat Verma Commented Sep 7, 2021 at 11:40
Add a comment  | 

6 Answers 6

Reset to default 16

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

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

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

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

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

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

You can use the next reg: ^(http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/)?[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$

Here is an example: https://www.regextester.com/93652

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

regex accept url without http or https

[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@%_\+.~#?&//=]*)

In HTML5

<input pattern="[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@%_\+.~#?&//=]*)" type="text>
发布评论

评论列表(0)

  1. 暂无评论