javascript - 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。表达式有什么问题?
解决方案
似乎您对它的使用?
正在抛弃它。添加?
使前面的字符(或字符集)可选。如果你想匹配“只接受数字、一个小数点和小数点后一个数字。”,表达式看起来更像这样:
/\d+\.\d/g
可以读作“一个或多个数字,字面'.',一个数字,全局看”。
推荐阅读
- python - 对 API URL 的 Python 获取请求返回 422 错误,但在浏览器上没有问题。潜在的服务人员问题?
- c++ - C++ 与关系条件混淆的问题,我没有得到什么?
- javascript - AWS Cognito - AdminInitiateAuth 与 InitiateAuth
- javascript - 如何将局部变量传递给全局函数
- java - 如何解决android改造2中通过api注册时得到响应400的错误
- reactjs - moment.js 解析字符串'2017 年 7 月 15 日,下午 3:12:09' fromNow()
- selenium - 在 Winium 中为 WiniumDriver 设置超时
- javascript - 使用 VBA 插入标签值
- python - 从机场网站抓取航班数据表失败
- reactjs - 如何在 React Native 中做 WebView?