简体   繁体   English

Javascript 正则表达式删除小数点后的尾随零

[英]Javascript regex remove trailing zeroes after decimal

I know this has been asked many times and I did find a solution, value.replace(/^([\d,]+)$|^([\d,]+)\.0*$|^([\d,]+\.[0-9]*?)0*$/, "$1$2$3") .我知道这已被问过很多次,我确实找到了解决方案, value.replace(/^([\d,]+)$|^([\d,]+)\.0*$|^([\d,]+\.[0-9]*?)0*$/, "$1$2$3")

But... I'm no regex expert so I'm just curious as to why this doesn't work /[\.0]+$/ ... 10 should return 10 but I just can't figure out how to exclude whole numbers that end with 0s.但是...我不是正则表达式专家所以我很好奇为什么这不起作用/[\.0]+$/ ... 10 应该返回 10 但我只是不知道如何排除以 0 结尾的整数。

1.7500, 1.1010, 1.0000, 10 1.7500, 1.1010, 1.0000, 10

1.75, 1.101, 1, 1 1.75, 1.101, 1, 1

You might shorten the pattern to match either a dot with only zeroes, or use a non greedy match for the digits with a capture group and match optional trailing zeroes.您可能会缩短模式以匹配仅包含零的点,或者对具有捕获组的数字使用非贪婪匹配并匹配可选的尾随零。

If you want to match digits and comma's the first \d+ can also be [\d,]+ as you already have in your pattern.如果你想匹配数字和逗号,第一个\d+也可以是[\d,]+你已经在你的模式中。

If there should be at least a single digit after the dot, then the quantifier can be a plus .\d+?如果点后至少应有一个数字,则量词可以是加号.\d+?

^(\d+)(?:\.0+|(\.\d*?)0+)$

See a regex 101 demo .请参阅正则表达式 101 演示

 [ "1.7500", "1.1010", "1.0000", "10" ].forEach(s => console.log(s.replace(/^(\d+)(?:\.0+|(\.\d*?)0+)$/, "$1$2")) );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM