8

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

1
  • new RegExp('^(?:ht|f)tp://[^/\\s]\\S*$', 'i') or new RegExp('^(?:ht|f)tp://[^/\\s]+(?:/[^/\\s]+)*/?$', 'i') Commented Mar 15, 2021 at 10:02

2 Answers 2

5

With your shown samples only, could you please try following.

^(https?|ftp):\/\/(?!\W*www\.)\S+$

Here is the Online demo of above regex

Explanation: Adding detailed explanation for above regex.

^(https?|ftp):  ##Checking if value starts with http(s optional here to match http/https) OR ftp.
\/\/            ##Matching 2 // here.
(?!\W*www\.)    ##Checking a negative lookahead to see if \W matches any non-word character (equivalent to [^a-zA-Z0-9_]) then www with a dot is NOT in further values.
\S+$            ##matches any non-whitespace character will end of the value here.
Sign up to request clarification or add additional context in comments.

Comments

3

Here's my regex for your URL;

I looked for valid URL characters and added them to my Regex

const regex = /^(http|ftp):\/{2}([\w\d]+[-\._~:/?#\[\]@!$&'()*+,;%=]*)*$/i;
const tests = [
  "http://example.com",
  "http://example.com/path1/path2?hello=1&hello=2",
  "http://a",
  "http://abc",
  "http:/example.com",
  "http://exampl e.com",
  "http:// exampl e.com",
  "http://example.com ",
  "http:// example.com",
  "http:///www.example.com"
];

console.log(tests.map(testStr => regex.test(testStr)));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.