I'm trying to parse numbers between 1 and 10,000,000 which can be straight digits (e.g. 123456) or with separating commas (1,234,567) between groups of 3 digits. The commas could also be spaces (1 234 567) or periods (1.234.567) but consistently used. I have written the following:
<script type="text/javascript">
var re = /(\d{1,3})[ |\,|\.]?(\d{3})(?:[ |\,|\.]?(\d{3}))?/i;
function testStr(input) {
var str = input.value;
var newstr = str.replace(re, '[1]: $1\n[2]: $2\n[3]: $3');
alert(newstr);
}
</script>
This works well, except that it also parses input such as 1234,567,890 or 1,234,5678 The groups of 4 consecutive digits should not be allowed. Why is this happening? Thanks for any help.
1,234.456 789it has each of the separators but they are not consistent. It does conform to the regex, though. You can write a regular expression to reject that but it's not going to be pretty and easy to maintain, since you'd need a separate branch for each separator. It'd be easier to parse the number and try to find the separators, then see if they conform as part of other validations.1,00,000,00,00,000