How do I have regex to match exact multiple domains without anything in front or end?

Viewed 3211

I'd like to whitelist domains and I have this list as

(domain1.com|domain2.com)

However, it will still match to

ci.domain1.com

https://regex101.com/r/A2IOJE/1/

I'm writing the code in node.js

Here's the code

new RegExp('(domain1.com|domain2.com)', 'igm').test('ci.domain1.com');
2 Answers

You just need to add ^ (start of string) & $ (end of string):

/^(domain1.com|domain2.com)$/

console.log(
new RegExp('^(domain1.com|domain2.com)$', 'igm').test('ci.domain1.com'),
new RegExp('^(domain1.com|domain2.com)$', 'igm').test('domain1.com'),
new RegExp('^(domain1.com|domain2.com)$', 'igm').test('domain2.com')
)

With anchors and optional www matching at the start you can use this regex:

/^(?:www\.)?(?:domain1|domain2)\.com$/i

Also dot before com needs to be escaped to avoid matching any character.

RegEx Demo

RegEx Breakup:

  • ^: Start
  • (?:www\.)?: Match optional www at the start of domains
  • (?:domain1|domain2): Match domain1 or domain2
  • \.com: Match literal text .com
  • $: End
Related