All characters in a string must match regex

You need * or + quantifier after your character class and anchors:

/^[xX<>=|0-9&()\s.]*$/.test(expression)
 ^                 ^^

Now, it will match

  • ^ – start of string
  • [xX<>=|0-9&\s().]*zero or more (if you use +, one or more) of the chars defined in the char class
  • $ – end of string.

Short demo:

console.log(/^[xX<>=|0-9&\s().]*$/.test("a.1"));
console.log(/^[xX<>=|0-9&\s().]*$/.test("(x>1) && (x<2)"));

Note I added \s to match whitespaces, too.

Leave a Comment