KOMPX.COM or COMPMISCELLANEA.COM   

Add thousands separator into numbers (JavaScript)

Putting a delimiter at every three digits in integers, consisting of consecutive digits, by means of JavaScript. The thousands separator used in the example is a comma:

12312312
1231231
123123
12312
1231
123
12
1

HTML code:


<div class="example">
	<div>12312312</div>
	<div>1231231</div>
	<div>123123</div>
	<div>12312</div>
	<div>1231</div>
	<div>123</div>
	<div>12</div>
	<div>1</div>
</div>

JavaScript code:


<script>
var cells = document.querySelectorAll('.example div');

for ( var cell of cells ) {
	var number = cell.textContent;
	// Adding the delimiter
	number = number.replace(/(\d)(?=(\d\d\d)+(?!\d))/g, '$1,');
	// Printing the result
	cell.textContent = number;
}
</script>

Links

  1. How to Add a Thousandths Place Comma (Every Three Digits) in JavaScript typeofnan.dev/how-to-add-thousandths-place-comma-every-three-digits-in-javascript/

Browser support

Windows
Edge 12.0+
Firefox 13.0+
Google Chrome 38.0+
Opera 25.0+
Linux
Firefox 13.0+
Google Chrome 38.0+
Opera 25.0+
iOS
Safari 7.0+
Android
Samsung Internet 3.0+
Chrome 38.0+
Firefox 14.0+
Opera 25.0+

More