Alex Rivera | Logout

Regex javascript, why dot and comma are matching for \

Asked 2011-03-29T08:13:11.770
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

Edit
Report

1 Answer

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+)?$/
answered 2011-03-29T08:17:37.323

Your Answer