user5718206
user5718206

Reputation:

Regular Expression dot and comma issue

I have this piece of code:

if(calcValue.search('[^0-9\*\+\-\/]') > -1) {
    jQuery('.output-field').text('Error: you can use only numbers and "+", "*", "-", "/" symbols');
  }

And this regular expression:

[^0-9\*\+\-\/]

must exclude all the symbols, except 0-9 digits and symbols: +, -, * and / but somehow it doesn't exclude dots and commas. How to exclude dots and commas too?

You can also check the code here: there will be error message if you put in the input anything except numbers, allowed symbols and for unknown reasons dots and commas.

Upvotes: 3

Views: 1405

Answers (2)

trincot
trincot

Reputation: 350270

You can pass search a string as you do, but the - in your regular expression works as a range (the escapes are resolved in the string literal, so they make no difference for the regular expression):

[^0-9*+-/]

So your class forbids 0 to 9, *, + to /, and that last range includes a dot and comma (and also the hyphen). So you should move the hyphen to the last position:

[^0-9*+/-]

Or, you should double escape the hyphen (once for the string literal, and again for the regular expression):

'[^0-9*+\\-/]'

Upvotes: 2

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324650

You are using String.prototype.search incorrectly. It expects a regex - either a /regex literal/ or a new RegExp object - but you are giving it a string.

Per the documentation, the passed non-regex is implicitly converted to one using new RegExp(arg).

You are passing in the string literal '[^0-9\*\+\-\/]', which becomes the string [^0-9*+-/]. This is then implicitly passed as new RegExp('[^0-9*+-/]') and the resulting character class includes +-/, which expands to +,-./ and this is where the comma and dot are allowed in.

I have two pieces of advice here.

The first, and most obvious, is to always pass the expected data type. In this case, a regex.

The second is to be more prudent with your escapes. They can be finicky at the best of times and there are many traps to avoid - especially when parsing happens twice (once for the string, once for the regex). Quantifiers do not need to be escaped inside a character class, and the / delimiter doesn't need escaping except if you're using a /regex literal/. Furthermore, the - range thing doesn't need escaping if it is the first or last character in the character class.

Consequently, my proposed fix is:

if( calcValue.search(new RegExp('[^0-9/*+-]')) > -1)

Upvotes: 1

Related Questions