正则实现千位符分割

需要时常来温习温习

const numberToKilobitSeparator = targetNum => { 
let reg; 
if (/[^\d\.]/.test(targetNum)) return targetNum;  //匹配到不是数字直接返回
   reg = /\./.test(targetNum) ? 
                                /(\d{1,3})(?=(\d{3})+\.\d+)/g :  //小数匹配正则
                                /(\d{1,3})(?=(\d{3})+$)/g; //整数匹配正则
     return targetNum.toString().replace(reg, '$&,'); //```$&`` : 表示匹配到的结果。'javascript'.replace(/script/, '$&$&') ->  ‘javascriptscript’
} 

numberToKilobitSeparator(12345678) // '12,345,678' 

numberToKilobitSeparator(12345678.2345) // '12,345,678.2345'

  

  

附一张比较好的图(https://www.douban.com/note/620458767/)

   解释整数实现的过程,小数参照一下也能理解

 

 


引自链接:https://juejin.im/post/6844903904082313230

posted @ 2020-09-04 11:51  Angular踩坑者  阅读(273)  评论(0编辑  收藏  举报