正则实现千位符分割
需要时常来温习温习
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://juejin.im/post/6844903904082313230