2 Ways to Add Comma as Thousand Separator in JavaScript

If you are working with a simple website or a react application, There are 2 common situations where you have to add a comma as a thousand separators.

  1. Displaying Information from an API or something
  2. Add a comma to the input field after the user has finished typing.

Using the toLocalString Javascript method

You can use the built-in javascript function toLocalString to add a thousand separator commas if you are displaying information on a web page. Here is an example of the first situation.

If you are using react you can simply do the following code to make it work. You can read more about toLocaleString at https://developer.mozilla.org

Using Regular Expression to Add Thousand Separators in HTML Input

If you are trying to enhance the user experience of a web page, you might want to automatically add commas when someone enters a number like a price. Inserting a comma after someone has entered a number will increase user experience. Here is a simple example to insert a comma as a thousand separators.


The above example will insert a comma in the input field when someone has finished typing and focus gets out of the input. The event listener “blur” will work when the focus goes out of the text field.


You can either use the javascript built-in function toLocaleString or use a regular expression to insert a comma in a number. Both methods will do the job for you whether you are in a vanilla javascript or using any framework like react, angular or vue.

Leave a reply

Please enter your comment!
Please enter your name here