Why this regex '^[0-9]+\.?[0-9]*$' match for 12.2 and 12,2 ?
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
Why this regex '^[0-9]+\.?[0-9]*$' match for 12.2 and 12,2 ?
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
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));
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+)?$/
Since you write your regex in a string, you need to escape the slash.
regex = '^[0-9]+\\.?[0-9]*$';
Your regex should be
regex = /^[0-9]+\.?[0-9]*$/;
Consult https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/regexp for proper syntax.