canardman
canardman

Reputation: 3263

Regex javascript, why dot and comma are matching for \

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

Upvotes: 28

Views: 82637

Answers (4)

maerics
maerics

Reputation: 156444

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));

Upvotes: 58

Cristian Necula
Cristian Necula

Reputation: 1245

Your regex should be

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

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

Upvotes: 0

Stephen Chung
Stephen Chung

Reputation: 14605

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+)?$/

Upvotes: 12

Effata
Effata

Reputation: 2342

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

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

Upvotes: 2

Related Questions