JavaScript中的正则表达式货币值 [英] regex for money values in JavaScript
本文介绍了JavaScript中的正则表达式货币值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
暂时退出正则表达式
游戏。试图提出一些允许用户输入货币值的信息,无论是否带有美元符号或带有/不带逗号。例如,以下所有值都应该有效:
Been out of the regex
game for a while. Trying to come up with something that will allow the user to enter a money value either with/without dollar sign or with/without commas. For example, all the of the following values should be valid:
5
5.1
5.10
$5
500,000
500,000.1
500,000.10
$100,000,000.50
etc....
有人可以帮帮我吗?
推荐答案
这应该有效:
isValid = str.search(/^\$?[\d,]+(\.\d*)?$/) >= 0;
逗号放置稍微严格一些(例如拒绝3,2.10):
A little more strict with comma placement (would reject 3,2.10, for example):
isValid = str.search(/^\$?\d+(,\d{3})*(\.\d*)?$/) >= 0;
从中得到一个数字:
if(isValid) {
var num = Number(str.replace(/[\$,]/g, ''));
...
}
这篇关于JavaScript中的正则表达式货币值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文