首页 > 解决方案 > Firefox 中的 Javascript 正则表达式失败

问题描述

我用stackoverflow question的接受答案中的正则表达式编写了一个函数Allowing only numbers and one decimal

function allowDecimal(field) {
    setTimeout(function() {
        var regex = /\d*\.?\d?/g;
        field.value = regex.exec(field.value);
    }, 0);
}
<br>For input say 2.5, chrome will give 2.5 while firefox will give 25<br>
<input type="number" onkeyup='allowDecimal(this);' id="baths"  name="baths">

它应该只接受数字、一个小数点和一个小数点后的数字。该表达式在 Chorome 中运行良好,但在 Firefox 中失败。对于输入 2.5,在 Chorome 中它显示 2.5,但在 Firefox 中它会擦除点并给出 25。表达式有什么问题?

标签: javascriptregex

解决方案


似乎您对它的使用?正在抛弃它。添加?使前面的字符(或字符集)可选。如果你想匹配“只接受数字、一个小数点和小数点后一个数字。”,表达式看起来更像这样:

/\d+\.\d/g

可以读作“一个或多个数字,字面'.',一个数字,全局看”。


推荐阅读