Jared Eitnier Jared Eitnier - 1 year ago 82
Javascript Question

Javascript regex to match fully qualified domain name, without protocol, optional subdomain

I haven't been able to find this one and what I'm trying isn't quite working out for me.

I want to match only domains that:

  • don't contain a protocol (http, https, ftp)

  • optionally include a subdomain

  • don't start with a hyphen but can contain a hyphen

Example domains that would match:

  • domain.com

  • example.domain.com

  • example.domain-hyphen.com

  • www.domain.com

  • example.museum

Example domains that would not match:

  • http://example.com

  • subdomain.-example.com

  • example.com/parameter

  • example.com?anything

  • www.subdomain.domain.com

What I've currently got:


It's not matching protocols, allowing hyphen inside the domain, not allowing trailing characters after the TLD, and is allowing a subdomain (but only 1 character).

I still need to allow subdomains of any length, not allow www.subdomain.domain.com and not allow a leading hyphen.

dda dda
Answer Source


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download