I've run into an issue with a jQuery script I made for formatting the input of currency to proper 2 decimal places and a comma for 1,000's. It works perfectly in chrome, but when I tested in Edge the console log showed an error for "unexpected quantifier", and in firefox, the console shows error for "invalid regex group".
Here is the line that is throwing the error:
return value.replace(/(?!\.)\D/g, "").replace(/(?<=\..*)\./g, "").replace(/(?<=\.\d\d).*/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ",");
This is the full function:
$('#sg-amount').on('change click keyup input paste',(function (event) {
$(this).val(function (index, value) {
return value.replace(/(?!\.)\D/g, "").replace(/(?<=\..*)\./g, "").replace(/(?<=\.\d\d).*/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ",");
});
}));
EDIT
This question is different than others as it does a few things:
1. It adds commas
2. Allows decimals
3. Limits the decimal place to 2 digits.
4. Does it all on Keyup
The other solutions I have found on stackoverflow do not do ALL of those things. I want to continue using jQuery and do not want to use Javascript. I like the simplicity of this code and don't want 500 lines of code to make it work.
It works perfectly in chrome, but does not work in Edge, or Firefox. I haven't tried any other browsers yet.
EDIT 2
Based on comments below, maybe this will help me more. Here is what I am wanting to accomplish with each replace:
.replace(/(?!\.)\D/g, "")
deletes all non numeric characters except .
.replace(/(?<=\..*)\./g, "")
removes all extra . except the first .
.replace(/(?<=\.\d\d).*/g, "")
deletes everything after 2 decimal places
.replace(/\B(?=(\d{3})+(?!\d))/g, ",")
inserts commas at appropriate places
Since some of these calls are causing errors in certain browsers, is there a better string to use in each replace that is cross browser friendly?