本文介绍了如果操作数有小数,正则表达式可防止逗号分隔符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现了这个正则表达式函数,它为算术表达式添加了千位逗号分隔符.

I found this regex function which add thousand comma separator for an arithmetic expression.

function numberWithCommas(x) {
    return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}

console.log(numberWithCommas("1000")); // ok
console.log(numberWithCommas("1000.03")); // ok
console.log(numberWithCommas("1000.03+2300")); // ok
console.log(numberWithCommas("1000.03+0.2300")); // not ok

但是如果操作数有十进制,我不想添加任何逗号分隔符.我应该如何相应地修改这个正则表达式?

But if the operand has decimal, I do not want to add any comma separator. How should I modify this regex accordingly?

p/s 数学运算符可以是 +,-,*,/

p/s the math operator can be +,-,*,/

推荐答案

一种选择是使用 替换 回调函数并匹配 1+ 次零后跟一个点和零.

One option could be using replace with a callback function and match 1+ times a zero followed by a dot and zero.

如果匹配,则在替换中返回,否则返回逗号.

If that is matched, return it in the replacement, else return a comma.

\b0+\.\d+(?:\.\d+)*|\B(?=(\d{3})+(?!\d))

正则表达式演示

function numberWithCommas(x) {
  const regex = /\b0+\.\d+(?:\.\d+)*|\B(?=(\d{3})+(?!\d))/g;
  return x.toString().replace(regex, (m) => m !== "" ? m : ",");
}

console.log(numberWithCommas("1000"));
console.log(numberWithCommas("1000.03"));
console.log(numberWithCommas("1000.03+2300"));
console.log(numberWithCommas("1000.03+0.2300"));

这篇关于如果操作数有小数,正则表达式可防止逗号分隔符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 09:32