简体   繁体   English

JavaScript正则表达式数字与包含单个零的字符串不匹配

[英]JavaScript Regular Expression digits not matching string containing single zero

I'm using the JavaScript regular expression: 我正在使用JavaScript正则表达式:

val.match(/\d*$/)

It works as expected for all numbers expect when the string is "0". 对于字符串为“ 0”时预期的所有数字,它均按预期方式工作。 A single zero value does not match. 单个零值不匹配。 How do I include that? 如何包括在内?

Test case: 测试用例:

<html>
<head>
<script src="scripts/jquery-1.5.1.min.js" type="text/javascript"></script>
</head>
<body>

<input type="text" id="txtRange" />
<div id="result" />

<script type="text/javascript">


    var rangeValidate = function (val, min, max) {
        if (val == "") {
            return "You must specify a number between " + min + " and " + max;
        } else if (val.match(/\d*$/) == false) {
            return "You must specify a number between " + min + " and " + max;
        } else if ((val < min) || (val > max)) {
            return "You must specify a number between " + min + " and " + max;
        } else {
            return "";
        }

        return "You must specify a number between " + min + " and " + max;
    }

    $('#txtRange').bind('change', function(){
            var value = $('#txtRange').val();
            var resultText = rangeValidate(value, 0, 8);
            $('#result').html(resultText);
    });

</script>
</body>
</html>

It matches, "0".match(/\\d*$/) returns the array ["0"] which when used in comparison is converted to its string representation "0" . 它匹配"0".match(/\\d*$/)返回数组["0"] ,在比较中将其转换为字符串表示形式"0"

But in JavaScript, the string `"0"` is "falsy", meaning it evaluates to `false` in a boolean context. 但是在JavaScript中,字符串“ 0”是“ falsy”,这意味着它在布尔上下文中的值为false。

Edit: Ok, the string is not "falsy". 编辑:好的,字符串不是“ falsy”。 Still, there is some conversion going on which eventually has the effect that "0" == false evaluates to true . 仍然有一些正在进行的转换,最终导致"0" == false评估为true

You should use .test() [docs] (which always returns a boolean value) instead and/or strict equality === : 您应该改用.test() [docs] (始终返回布尔值)和/或严格等于===

} else if (/\d*$/.test(val) === false) {

If the whole string should be a number, you should also anchor the expression at the beginning of the string: 如果整个字符串应为数字,则还应将表达式锚定在字符串的开头:

/^\d*$/

Or don't use regex at all and use + to convert the value to a number. 或者根本不使用正则表达式,而使用+将值转换为数字。 If it cannot be converted (because it contains something else than digits) it will return the special value NaN (not a number). 如果它不能转换(因为它包含数字以外的东西),它将返回特殊值NaN (不是数字)。 You're code would become: 您的代码将变成:

var rangeValidate = function (val, min, max) {
    val = +val;
    if (isNaN(val) || (val < min) || (val > max)) {
        return "You must specify a number between " + min + " and " + max;
    } else {
        return "";
    }
}

See a DEMO . 看到一个演示

Okay, wow... just weird. 好吧,哇...真奇怪。 What's actually going on: 实际发生了什么:

The result from a .match is an array. .match的结果是一个数组。 Since you have a single match, your result is ['0'], and ['0'].toString() === '0' == false. 由于您只有一个匹配项,因此结果为['0']和['0']。toString()==='0'== false。

In ANY other case (if you matched a paren set in the regex, etc), this would be NOT equal false regardless of whether or not it was zero. 在任何其他情况下(如果您匹配了正则表达式中设置的括号),则无论它是否为零,都将不等于false。

Now for the weird bit: 现在,奇怪的是:

> ['0'] == false
true
> !!['0']
true

So the == operator forces an implicit .toString() where as the ! 因此,==运算符会强制使用一个隐式.toString(),其中! operator doesn't! 操作员没有!

0 == false returns true in javascript. 0 == false在javascript中返回true。 0 === false will return false in javascript. 0 === false将在javascript中返回false。

Change your val.match(/\\d*$/) == false in val.match(/\\d*$/) === false . val.match(/\\d*$/) == false中更改您的val.match(/\\d*$/) == false val.match(/\\d*$/) === false I don't know if this will fix your problem, but it's always good to keep this in mind. 我不知道这是否可以解决您的问题,但是牢记这一点总是很好的。

Try this:- 尝试这个:-

var rangeValidate = function (val, min, max) {
    if ( /^\d+$/.test(val) && val>=min && val<=max ) {
        return "";
    } else {
        return "You must specify a number between " + min + " and " + max;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM