Skip to content

数字格式化

Code

ts
const str = '100000000000';
// 100,000,000,000;

解析

ts
/**
 * str.replace(/(?=\d)/g, ',') => ',1,0,0,0,0,0,0,0,0,0,0,0'
 * 转换成匹配后3位
 * str.replace(/(?=\d{3}$)/g, ',') => '100000000,000'
 * 匹配0次或多次
 * str.replace(/(?=(\d{3})*$)/g, ',') => ',100,000,000,000,'
 * 去除首位
 * str.replace(/\B(?=(\d{3})*$)/g, ',') => '100,000,000,000'
 */
str.replace(/\B(?=(\d{3})*$)/g, ',')