Regex to match simple domain

^https?://([\w\d]+\.)?example\.com$

using code:

var result = /^https?:\/\/([a-zA-Z\d-]+\.){0,}example\.com$/.test('https://example.com');
// result is either true of false

I improved it to match like "http://a.b.example.com"


You can probably use to just match the domain name part of a URL:

/^(?:https?:\/\/)?(?:[^.]+\.)?example\.com(\/.*)?$

It will match any of following strings:

https://example.com
http://www.example.com
http://example.com
https://example.com
www.example.com
example.com

 

RegEx Demo

RegEx Details:

  • ^: Start
  • (?:https?:\/\/)?: Match http:// or https://
  • (?:[^.]+\.)?: Optionally Match text till immediately next dot and dot
  • example\.com: Match example.com
  • (\/.*)?: Optionally Match / followed by 0 or more of any characters
  • $: End