toLocaleString() works to insert commas in a textbox until I enter the eighth digit. The eight digit breaks the insertion of commas

I am not the best at Javascript but have been using it more to avoid web forms postbacks at my users requests. The user also requested commas inserted in an numeric field (no decimal digits) as they type. I used toLocaleString(). The insertion of commas works fine until I get to the eighth digit. At that point the number shrinks in size and goes back to four digits, There is a valid comma in this but obviously I need to be able to put in more than 7 digitis.
Here is the seven digit state of the field:
And here is the field when I add the number 8 to the end of the above number:

The following code fired from on the onkeyup event handles this number:

 var word = txtbox.value;
 word = word.replace(",", "");
 let num = word;
 formatted = parseInt(String(num)).toLocaleString();
 txtbox.value = formatted;

I have also tried functions i found on web posts and regex values. Some cases didnt work at atll but many of the cases involving regex also seemed to break once the eighth digit is entered. Oddly all the examples I’ve seen on the web seem to involve no more than seven digits.
I tried adding “en-us” to the toLocaleString() as well as setting maxiumnsignificantdigits to 9. The result was the same.
8 seems to be a magic number and the solution is probably buried in some obscure documentation somewhere.
Any help would be appreciated.


Welcome to this forum.

By using:
word = word.replace(",", "");
you are replacing only the first comma.

Use a regular expression with global flag (g):
word = word.replace(/,/g,"");

BTW: Things still go wrong if you enter decimal digits.

Hi @neilnewtonfig,

You also have string.replaceAll

const num = '1,234,5678'

formatted = parseInt(num.replaceAll(',', ''), 10).toLocaleString();
console.log(formatted) // 12,345,678

I would use regex to be sure only digits remain in the string I pass to localString(). So the user can also type characters and special chars and my function still works fine.

yourString = yourString.replace ( /[^0-9]/g, '' );

Albeit not foolproof, you could also use an input type of number to stop the user typing something silly in the first place.

That or set a pattern on the input.