都什么年代了,还在用正则做千分位分隔吗?(冷门但是有用的toLocaleString,js原生API就能实现千分位分隔)
场景:
实际开发中,对于一些金额相关的数字,通常需要前端实现千分位分隔。
即:实际数字位12345678,页面上展示出来则需要为12,345,678
常见的实现方法:
1.正则
代码实现:
function thousand(num) {
return (num+"").replace(/\d(?=(\d{3})+$)/g, "$&,")
}
使用:
thousand(12345678)//=>'12,345,678'
2.js硬刚
代码实现:
function thousand(number) {
const arr = (number+'').split('.');
const int = arr[0].split('');
const fraction = arr[1] || ''
let returnStr = '';
int.reverse().forEach(function (item, index) {
if (index !== 0 && index % 3 === 0) {
returnStr = item + ',' + returnStr;
} else {
returnStr = item + returnStr;
}
});
return returnStr + (!!fraction ? '.' + fraction : '');
}
使用:
thousand(1234556)//=>'1,234,556'
船新的方法,冷门但是有用的toLocaleString
使用:
Number(123456789).toLocaleString()//=>'123,456,789'
有什么事情是不需要自己动手写方法,直接用原生API就能解决更让人身心舒畅的呢?
扩展:
不光Number可以使用toLocaleString,Date格式化也可以使用,并且toLocaleString还能接收参数实现不同效果,具体的请点此查看MDN,因为个人觉得其他功能都不是太实用,所以不在此赘述。