The Javascript regular expression implementation adds a thousand separator for a number

  • 2020-05-12 02:08:56
  • OfStack

Recently, I saw an interview (written test) question that used js to realize the thousands separator of Numbers on the Internet, so I wrote a method to realize it by using "regular +replace" :


 var thousandBitSeparator = function(numStr){
     var b = /([-+]?\d{3})(?=\d)/g;
     return numStr.replace(b, function($0, $1){
         return $1 + ',';
     });
 }

Support plus and minus sign matching, decimal point differentiation, if there is an error, we hope to point out: -D

Attached is an implementation method of other netizens


<script language="JavaScript" type="text/javascript"> 
function formatNumber(num){ 
 if(!/^(\+|-)?(\d+)(\.\d+)?$/.test(num)){ 
  return num; 
 } 
 var a = RegExp.$1,b = RegExp.$2,c = RegExp.$3; 
 var re = new RegExp().compile("(\\d)(\\d{3})(,|$)"); 
 while(re.test(b)){ 
  b = b.replace(re,"$1,$2$3"); 
 } 
 return a +""+ b +""+ c; 

var num=1234567/3; 
alert("num="+num+" . 4 Give up 5 In: "+Math.round(num)+" , two significant digits: "+num.toFixed(2)+" , add the thousands separator: "+formatNumber(num)); 
</script> 

That's all for this article, I hope you enjoy it.


Related articles: