我正在尝试使用正则表达式来确保输入是数字或浮点数。如果用户输入了美元符号,我希望javascript将其删除并返回true。如果用户输入逗号,则返回false。
这是我尝试的(但它总是返回false):
var validAmount = new RegExp('/[^0-9.]/g');
validAmount.test(numberAmount);
if(!validAmount.test(parseFloat(numberAmount))){
alert("bad Amount");
}
期望的输出:
Input: 232 //output: true
Input: 1212.23 //output:true
Input: $12.23 //(remove $ sign and output:true)
Input: a23 //output:false
Input: 1,000 //(output:false)
答案 0 :(得分:1)
我认为这个正则表达式可能适合你:
amount.replace(/^\$?([\d]+\.?[\d]*)$/, '$1');
我的意思是它将返回有效字符串(当有效输入时)或无效时返回任何内容(false)。
答案 1 :(得分:1)
您似乎在寻找类似/^(\$?(\d+(\.\d+)*)?|.*)$/
;
> exp = /^(\$?(\d+(\.\d+)*)?|.*)$/
> '232'.replace(exp, '$2');
'232'
> '1212.23'.replace(exp, '$2');
'1212.23'
> '$12.23'.replace(exp, '$2');
'12.23'
> 'a23'.replace(exp, '$2');
''
> '1,000'.replace(exp, '$2');
''
答案 2 :(得分:0)
/^\$?(\d+|\d*\.\d+)$/
这也可能有用。
var regex=/^\$?(\d+|\d*\.\d+)$/;
alert(regex.test("232"));