Mandeep Singh
Mandeep Singh

Reputation: 8224

javascript regular expression for domain name

I am trying to write a regular expression for matching domain names like these:

NS1.MDNSSERVICE
NS.INMOTIONHOSTING

And ignore other entries, especially the ones that don't contain any dot(.)

However, the result I am getting is not consistent with my understanding. Here is my code:

var regex = new RegExp("^[a-z0-9-]+\.[a-z0-9-]+(\.[a-z0-9-]+){0,2}$", "i");
"file".match(regex);

output

[ 'file',
  undefined,
  index: 0,
  input: 'file' ]

My understanding is that:

^ : match the beginning of line
[a-z0-9-]+ : match one of more occurrence of alphanumeric or hyphen(-).
\. : match the literal dot(.)

Since I am explicitly mentioning to match the dot(.), not sure why is it returning the match with keywords like "file".

Upvotes: 1

Views: 314

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626806

You need to use a literla notation or double-escape the metacharacters in a constructor notation. A literal notation is preferable here since your pattern is not built dynamically:

/^[a-z0-9-]+\.[a-z0-9-]+(\.[a-z0-9-]+){0,2}$/i

See snippet:

var regex = /^[a-z0-9-]+\.[a-z0-9-]+(\.[a-z0-9-]+){0,2}$/i;
console.log("file".match(regex)); // --> null
console.log("NS.INMOTIONHOSTING".match(regex)); 
// --> ["NS.INMOTIONHOSTING", undefined, index: 0, input: "NS.INMOTIONHOSTING"]

Upvotes: 2

Related Questions