How to Add Delimiters in JavaScript using Regex

There s no native method in JavaScript to add delimiters like having commas in numbers. In this article, we will focus on the JavaScript function of ‘formatNumber()’. See the code below:

 function formatNumber(rawNumber, decimal, delimiter) 
     var temp = parseFloat(rawNumber).toFixed(decimal);
     var partArray = temp.toString().split("."); 
     partArray[0] = partArray[0].toString().replace(/\B(?=(\d{3})+(?!\d))/g, delimiter); 
     return partArray.join("."); 

Since the addition of delimeters only concerns the whole number part of the number string we will split the number string into a whole number part and the decimal number part.

We can also say: Start from the right most position of the whole number, find the 3-digit block, the add a delimeter to the left boundary of the block. Then start from the right most position again, find the first 6-digit block, then add a delimeter to the left boundary of the blog. Repeat the process.


Read the rest of the tutorial here:

Leave a Reply

Your email address will not be published. Required fields are marked *