28

Why this regex '^[0-9]+\.?[0-9]*$' match for 12.2 and 12,2 ?

jsFiddle

var dot = '12.2',
    comma = '12,2',
    regex = '^[0-9]+\.?[0-9]*$';

alert( dot.match(regex) );
alert( comma.match(regex) );

While it works on regexpal.com

canardman
  • 3,103
  • 6
  • 26
  • 28

4 Answers4

58

Because the variable regex is a string the escape sequence \. is just ., which matches any character (except newline). If you change the definition of regex to use RegExp literal syntax or escape the escape character (\\.) then it will work as you expect.

var dot = '12.2'
  , comma = '12,2'
  , regex = /^[0-9]+\.?[0-9]*$/;
      // or '^[0-9]+\\.?[0-9]*$'
alert(dot.match(regex));
alert(comma.match(regex));
David Jones
  • 4,766
  • 3
  • 32
  • 45
maerics
  • 151,642
  • 46
  • 269
  • 291
12

Are you sure you don't need to escape the back-slash? It is in a string, you know...

regex = /^[0-9]+\.?[0-9]*$/

or

regex = "^[0-9]+\\.?[0-9]*$"

Actually, I'd recommend that you write it this way:

regex = /^\d+(\.\d+)?$/
Stephen Chung
  • 14,497
  • 1
  • 35
  • 48
2

Since you write your regex in a string, you need to escape the slash.

regex = '^[0-9]+\\.?[0-9]*$';

Effata
  • 2,352
  • 2
  • 15
  • 11
0

Your regex should be

regex = /^[0-9]+\.?[0-9]*$/;

Consult https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/regexp for proper syntax.

Cristian Necula
  • 1,247
  • 13
  • 17