Home > Back-end >  Add optional group of characters in regex
Add optional group of characters in regex

Time:10-13

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.

Thanks

CodePudding user response:

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.

  • Related