Dot and comma

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 is the regex:

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

      

should exclude all characters except 0-9 digits and symbols: +, -, * and /, but somehow this doesn't exclude periods and commas. How to exclude periods and commas?

You can also check the code here : an error message will appear if you enter anything other than numbers, allowed characters and, for unknown reasons, periods and commas.

+3


source to share


2 answers


You are using it String.prototype.search

wrong. It expects a regex - either an object /regex literal/

or new RegExp

, but you give it a string.

In the documentation , a non-regex passed in is implicitly converted to one using new RegExp(arg)

.

You are passing in a string literal '[^0-9\*\+\-\/]'

that becomes a string [^0-9*+-/]

. It is then implicitly passed as new RegExp('[^0-9*+-/]')

, and the resulting character class includes +-/

, which expands to +,-./

, which means comma and period are allowed.

I have two tips here.



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

The second should be more sensible with your shoots. They can be good at the best of times, and there are many pitfalls to avoid - especially when parsing happens twice (once for a string, once for a regex). Quantifiers do not need to be escaped within a character class and the delimiter /

does not need escaping except when you use /regex literal/

. Also, a range item -

does not need to be escaped if it is the first or last character in a character class.

Hence my suggested fix:

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

      

+2


source


You can pass a search

string just like you, but -

in your regex works like a range (screens are allowed in a string literal, so they don't make any difference to the regex):

[^0-9*+-/]

      

Thus, your class is prohibited 0

to 9

, *

, +

to /

, and the last range includes point and comma (and the hyphen). Therefore, you must move the hyphen to the last position:



[^0-9*+/-]

      

Or you have to double the escape hyphen (once for string literal and again for regex):

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

      

+2


source







All Articles