1、正则截取两个字符串间的值
let str="sdfsdf:12545.sdafs.dfsdf:98794564.sdfdf:"; let getStr = str => { let reg = /:(.+?)\./g; let arr = str.match(reg); let newArr =[] for (let i =0;i<arr.length;i++) { newArr.push(arr[i].replace(/(:|\.)/g, '')) } return newArr; } console.log(getStr(str)) // ["12545", "98794564"]
优化后
let str="sdfsdf:12545.sdafs.dfsdf:98794564.sdfdf:"; let getStr = str => { let reg = /:(.+?)\./g; let arr = str.match(reg); return arr.join(',').replace(/(:|\.)/g, ''); } console.log(getStr(str))
2、数字格式化
let num = '1234567890' let format = num.replace(/\B(?=(\d{3})+(?!\d))/g, ',') console.log(format) // 1,234,567,890 /** */\B(?=(\d{3})+(?!\d))/g:正则匹配边界\B,边界后面必须跟着(\d{3})+(?!\d); *(\d{3})+:必须是1个或多个的3个连续数字; *(?!\d):第2步中的3个数字不允许后面跟着数字; *(\d{3})+(?!\d):所以匹配的边界后面必须跟着3*n(n>=1)的数字。 **/
3、金额大小写转化
let arr = ['零', '壹', '贰', '叁', '肆', '伍', '陆','柒', '捌', '玖', '拾']; let str ='112'; str = str.replace(/\d/g, function () { return arr[arguments[0]]; }); /* * 第一次执行:大正则捕获的是2,返回的是ary[2] --> '贰' * 第二次执行:大正则捕获的是0,返回的是ary[0] --> '零' * ..... */ console.log(str);