I need a simple JavaScript regular expression to match URLs in a string. This is what I have at the moment:
/(https?://)?[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9].[^s]{2,}/gi
This works 99% of the time for any URL that contains 3 or more characters, for example all of these work:
-
abc.com
-
abcd.com
but I can’t get it to work for a URL with 2 characters:
-
ab.com
-
ow.ly
I’m using the match method like this:
let regex = /(https?://)?[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9].[^s]{2,}/gi
let matches = "http://ab.com".match(regex)
2
This part of your regex:
[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]
means, “match a letter or a digit, followed by one or more letters or digits, followed by a letter or a digit”. Thus it will not match a 2-character string like “ab”. I’m not sure why the third group is there, but it doesn’t make sense; in fact in my opinion all you need is
[a-zA-Z0-9-]+
because you probably want to match “x.com” also.
3