首页 > 解决方案 > jQuery正则表达式删除不符合要求的数字

问题描述

我正在尽力为我的正则表达式问题找到解决方案,但失败了。当输入不是浮点数时,我想用空白(实时)替换我的输入。

这就是我为整数输入所做的。

$(document).on("keyup", ".onlyInteger", function(event){
if (!(event.keyCode >=37 && event.keyCode<=40)) {
    var inputVal = $(this).val();
    inputVal = inputVal.replace(/[^0-9]/gi,'');

    $(this).val( addComma(inputVal) );
}

});

我想应用此代码用 '' 替换非浮点输入,但找不到浮点数的否定正则表达式。

我想要得到的结果。

10,000 --> true
10 --> true
0.1 --> true
1.23234 --> true
1,231.123 --> true
0.000001 --> true
1.000 --> true


. at the beginning --> false (replace with blank)
0001.2 --> false (replace with blank)
-1.01 --> false (replace with blank)
+2.3 --> false (replace with blank)
characters --> false (replace with blank)
1.1.1.1 --> false (replace with blank)

任何帮助,将不胜感激。谢谢。

标签: javascriptjqueryregex

解决方案


尝试正则表达式 ^(([0-9,]+)|(([1-9,]+|0)\.\d+))$

const regex = /^(([0-9,]+$)|(([1-9,]+|0)\.\d+))$/gm
const str = '10'
const numbers = regex.test(str) ? str : ''
console.log(numbers)


推荐阅读