我有一个字段,用户需要在其中输入窗口的宽度。它需要介于 16.75 和 48 之间,并且只能以 .25 为增量(因此它必须以 .00、.25、.50、.75 结尾)。我尝试了以下方法来测试数字 31.25 上的正则表达式,但全部返回 false。我在网上搜索过,但找不到对像我这样的正则表达式新手的帮助。有人可以帮我解决这个问题吗?
这是字段:
<input type="text" id="windowWidth" onchange="basePrice()">
这是JS:
function basePrice()
{
var windowWidth = document.getElementById("windowWidth").value;
var windowHeight = document.getElementById("windowHeight").value;
if (windowWidth != "" && windowWidth > 16.75 && windowWidth < 48)
{
alert(/^\d{2}\.[00]$/.test(windowWidth));
alert(/^\d{2}\.[25]$/.test(windowWidth));
alert(/^\d{2}\.[50]$/.test(windowWidth));
alert(/^\d{2}\.[75]$/.test(windowWidth));
}
else
{
alert("error");
exit;
}
}
最佳答案
删除正则表达式中用于字符类的[
和]
:
alert(/^\d{2}\.(?:00|25|50|75)$/.test(windowWidth));
例如:[00]
表示匹配文字 0 或 0
OR [25]
表示匹配 2 或 5
关于javascript - 如何使用正则表达式来测试特定的小数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19552081/