I'm writing a Regex to detect if a string starts with a valid protocol —lets say for now it can be http or ftp—.
The protocol has to be followed by ://, and one or more characters, with no white spaces in the string, ignoring case.
I have this Regex that is doing everything, except checking for white spaces in the string:
const regex = new RegExp('^(http|ftp)(://)((?=[^/])(?=.+))', 'i');
const urlHasProtocol = regex.test(string);
^(http|ftp) — checks for http or ftp at the beginning
(://) — is followed by "://"
((?=[^/])(?=.+)) — is followed by a string that
(?=[^/]) — doesnt start with "/"
(?=.+) — has one or more characters
Those must pass:
http://example.com
http://example.com/path1/path2?hello=1&hello=2
http://a
http://abc
Those must fail:
http:/example.com
http://exampl e.com
http:// exampl e.com
http://example.com // Trailing space
http:// example.com
http:///www.example.com
I'm trying to add the rule for the whitespaces. I'm trying with a look ahead that checks for non one or more white spaces in the middle or at the end: (?=[^s+$])
const regex = new RegExp('^(http|ftp)(://)((?=[^/])(?=.+)(?=[^s+$]))', 'i');
const urlHasProtocol = regex.test(string);
But this is not working properly.
Any advice will be welcome
new RegExp('^(?:ht|f)tp://[^/\\s]\\S*$', 'i')ornew RegExp('^(?:ht|f)tp://[^/\\s]+(?:/[^/\\s]+)*/?$', 'i')