-2

I used the below function to auto adding comma in text box (Such as: 124355 => 124,355)

function addCommas(num) {   
   return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}

And I use onKeyUp event:

<td><input type="text" onkeyup="this.value=addCommas(this.value);"/></td>

If I enter the number quickly this is ok. But, if I enter number slowly I got the below result:

124355 => 1,2,4,355
135298532 => 1,3,5,2,9,8,532

Can you help me fix this ?

vsync
  • 118,978
  • 58
  • 307
  • 400
taibc
  • 897
  • 2
  • 15
  • 39
  • you need to clean all commas before running the regex first.. – vsync Nov 26 '14 at 11:26
  • hi @tabic, you can try oninput event . – kuldipem Nov 26 '14 at 11:27
  • 1
    `'1,2,4,355'.split(',').join('')` and the do the regex – vsync Nov 26 '14 at 11:27
  • This has been very thoroughly covered here on SO before. I don't have time to search for you, but it's here, so keep looking. *Edit* Turns out all that was needed was to search your title and `site:stackoverflow.com` on A Famous Web Search Engine. – T.J. Crowder Nov 26 '14 at 11:28
  • But note that what you're passing into your `addCommas` function *isn't* a number, it's a string. You probably want to convert it to a number before converting it back to a string. – T.J. Crowder Nov 26 '14 at 11:30
  • Thanks everyone, @vsync: great ! It is successful when using: '1,2,4,355'.split(',').join('') and the do the regex – taibc Nov 27 '14 at 01:23

1 Answers1

2

I guess you should first remove all commas (with .replace()) from input and only afterwards apply the regex.

Łukasz Zwierko
  • 621
  • 7
  • 15
  • Thanks everyone, @vsync: great ! It is successful when using: '1,2,4,355'.split(',').join('') and the do the regex – taibc Nov 27 '14 at 01:22