Monfear
Monfear

Reputation: 11

Regexp alphabetical does not match

What is wrong with this code? It console.log all keys not only a-z.

const regExp = /[a-b]/;

document.body.addEventListener("keydown", (e) => {
  if (e.key.match(regExp)) {
  console.log(e.key);
   }
});

Upvotes: 0

Views: 26

Answers (1)

logi-kal
logi-kal

Reputation: 7880

[a-b] means "from a to b" or, in this case equivalently, "a or b" (since they are the only two characters in that range.

You are getting also other matches because, for instance, CapsLock contains the character a.

Use /^[ab]$/ instead (or /^[a-z]$/, if b was a typo).

Upvotes: 2

Related Questions