正则表达式替换浮点数中的多个句点 [英] regex replacing multiple periods in floating number
本文介绍了正则表达式替换浮点数中的多个句点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我输入这样的内容:a1.b22.333,我希望它输出:
If I enter something like this: a1.b22.333, I want it to output either:
1.22333或 122.333
1.22333 or 122.333
它去除了非数字字符和任何超过 1 的句点.
It gets rid of the non digit characters and any periods beyond 1.
我对此的最佳猜测是:
obj.value = obj.value.replace( /[^0-9\.{1}]+/g , '');
obj.value = obj.value.replace( /[^0-9\.{2,}]+/g ,'');
obj.value = obj.value.replace( /[^0-9\.(?=.*\.)]+/g ,'');
但是这些都是输出1.22.333
But these all output 1.22.333
我怎样才能摆脱那段额外的时间?
How can I get rid of that extra period?
感谢您的帮助.
推荐答案
你可以这样做:
obj.value = obj.value.replace(/[^\d\.]/g, "")
.replace(/\./, "x")
.replace(/\./g, "")
.replace(/x/, ".");
这会删除所有非数字、非句点字符,然后仅用x"替换第一个句点,然后删除所有其他句点,然后将xxx"改回句点.
This removes all non numeric, non-period characters, then replaces only the first period with "x", then removes all other periods, then changes "xxx" back to the period.
这篇关于正则表达式替换浮点数中的多个句点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文