Home  >  Q&A  >  body text

javascript - Regular expression /(\d)(?=(\d{3})+\.)/g

How to add a comma to every three digits of the number to the left of a floating point number, such as converting 12000000.11 into "12,000,000.11"?

function commafy(num){

  return num && num
      .toString()
      .replace(/(\d)(?=(\d{3})+\.)/g, function(, ){
          return  + ',';
      });

}
I don’t know how to understand this regular rule. /(d)(?=(d{3}) .)/g
Not sure how it works

伊谢尔伦伊谢尔伦2614 days ago583

reply all(1)I'll reply

  • 阿神

    阿神2017-05-19 10:37:23

    匹配/(\d)(?=(\d{3})+\.)/g数字后面是三个数字或者3的倍数个数字,后面跟小数点。d{3})+表示3的倍数个数字,如3个数字6个数字等,?=表示后面一定是3的倍数个数字

    reply
    0
  • Cancelreply