常用的正则表达式匹配

1.给数字加千分位逗号

'123456789.99888'.replace(/(?=(?!\b)(?<!\.\d+)(\d{3})+(\.\d+)?$)/g, ',')

2.保留固定的整数位和小数位

/**

*

* @param {z: 保留整数位数 y: 保留小数位数} param0

*/

function keepLen(num, {z, x} = {}) {

let regStr = `^${ z ? `(\\d{1,${z}})\\d*` : '(\\d+)' }${ x ? `((\\.\\d{1,${x}})\\d*)?` : '(\\.\\d+)?' }$`

let reg$ = '$1'

x && (reg$ += '$3')

let reg = new RegExp(regStr)

return num.toString().replace(reg, reg$)

}

console.log(keepLen(1234.556677, {z: 2, x: 3}))  // 12.556

console.log(keepLen(1234.556677, {x: 3}))  // 1234.556

console.log(keepLen(1234.556677, {z: 2})) // 12

console.log(keepLen(1234.556677))  // 1234

3.正则表达式给字符串去重

'abcacab'.replace(/(\w)(?=\w*\1)/g, '')

猜你喜欢

转载自blog.csdn.net/zsnpromsie/article/details/85804064