Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Add optional group of characters in regex

Hi there I was trying to check only www.facebook.com or facebook.com the rest is optional for the following criteria

const checkFacebookURL = new RegExp(^(https?:\/\/)?((w{3}\.)?)facebook.com?\/?([a-zA-Z0-9](.?))?([a-zA-Z0-9](.?)))

if (facebookRegex.test(e.target.value)) {
   setFacebook(e.target.value);
   setFacebookError(false);
} else if (e.target.value === '') {
   setFacebook(e.target.value);
   setFacebookError(false);
} else {
   setFacebookError(true);
}

I’m not that good with regex was reading the docs and trying to figure it out but no luck.
If someone could point me in the direction or better share an answer that would really help me.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thanks

>Solution :

I would use this pattern:

^(?:https?:\/\/)?(?:www\.)?facebook\.com(?:\/.*)?$

Explanation:

  • ^ from the start of the URL
  • (?:https?:\/\/)? optional http or https scheme
  • (?:www\.)? optional www subdomain
  • facebook\.com match facebook.com
  • (?:\/.*)? optional slash and subdirectory
  • $ end of the URL

Here is a working demo.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading