0

I write numeric value in input, and Regex catch up value and replace according to my regex. But it does not work correctly. I use the keyup event when I write numeric value and I need to fix from myregex correctly for every keyup events. It worked correctly until four digits, after that it's not working correctly.

I expected inside the input: 592,500,000

But It return like this error inside the input : 5,9,2,5,0,0,,000

You can check code snippet. Can you help for this?

Code Examples:

var myNum = document.getElementById('num');

myNum.addEventListener('keyup', function(e) {
  var dd = e.target.value.replace(/(?=(?:\d{3})+$)(?!^)/g, ',')
  myNum.value = dd;
  console.log(dd);
});

// I expect like this:
console.log('592500000'.replace(/(?=(?:\d{3})+$)(?!^)/g, ','));
<input type="text" id="num">
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
ht13
  • 633
  • 7
  • 19

1 Answers1

-1

You can first remove all commas so that the previous results do not affect the current result.

var myNum = document.getElementById('num');

myNum.addEventListener('keyup', function(e) {
  var dd = e.target.value.replace(/,/g, '').replace(/(?=(?:\d{3})+$)(?!^)/g, ',')
  myNum.value = dd;
  console.log(dd);
});
<input type="text" id="num">
Unmitigated
  • 76,500
  • 11
  • 62
  • 80