Reputation: 3129
I have a URL that I am using and trying to validate it with some regex and it keeps failing and I am unsure why that is
let a = "https://cdn-myCdn.azure.net/send-to-home4/";
let re = /^((https?|ftp|smtp):\/\/)?(www.)?[a-z0-9]+\.[a-z]+(\/[a-zA-Z0-9#]+\/?)*$/;
return re.test(a);
I have tried removing the www. but it was still failing
Upvotes: 1
Views: 69
Reputation: 626861
The main trouble is with your character classes that do not match a hyphen, [a-z0-9]
and [a-zA-Z0-9#]
, while your input contains them. Another major problem is that the [a-z0-9]+\.[a-z]+
pattern does not allow more than one single dot in the domain part of the URL, you need to put the [a-z0-9]+\.
part into a group and set a +
quantifier to the group. Note that [a-z0-9]
does not allow uppercase letters, you have them in the URL.
Note also that www.
matches www
and any char other than line break char, you need to escape the dot.
So, one possible variation that will work for you is
/^(?:(?:https?|ftp|smtp):\/\/)?(?:www\.)?(?:[\w-]+\.)+[a-z]+(?:\/[\w#-]+)*\/?$/
See the regex demo
NOTE: This is still a very restrictive URL pattern, only use it if you know all the URL you need to validate meet the following:
^
- start of string(?:(?:https?|ftp|smtp):\/\/)?
- an optional sequence of http
, https
, ftp
, or smtp
, followed with ://
(?:www\.)?
- an optional sequence of chars, www.
(?:[\w-]+\.)+
- 1 or more repetitions of:
[\w-]+
- 1 or more letters, digits or _
\.
- a dot[a-z]+
- 1+ lowercase ASCII letters(?:\/[\w#-]+)*
- 0 or more repetitions of:
\/
- a /
char[\w#-]+
- 1 or more letters, digits,
_,
#or
-`\/?
- an optional /
$
- end of string.Upvotes: 1