Easier way to have RegExp.test() return false for null values?

let regex = /[a-z]+/;
regex.test('a'); // true
regex.test(''); // false
regex.test(null); // true
regex.test(undefined); // true

So based on this link, Is it a bug in Ecmascript - /S/.test(null) returns true?, it looks like the null value is coerced to a string 'null'. WTF? Why on earth is this designed this way? I also can't find any documentation on this behavior. Is there a way to return false for null/undefined values (without hardcoding in checks for 'null', etc.)?


The argument of RegExp.test() is expected to be a string. If it isn't, it is converted to a string:

var regex = /[object Object]/;
console.log(regex.test({})); // true

If you're testing a variable, you could do:

regex.test(var || '')

so that it will default to the empty string if it's not set.


You can override test method.

old = regex.test
regex.test = function(str){
    str = str? str: "";
    return old.call(this, str);
}
regex.test(null);  // false

One way is to get your expected output is to check the value first and replace it with "" empty string in case of null or undefined

let regex = /[a-z]+/;
function test (inp){
    return regex.test(inp? inp: '');
}

test(null); // false
test(undefined); // false
链接地址: http://www.djcxy.com/p/94982.html

上一篇: 是否有任何标准JavaScript API或库以字符串对象的形式返回字符串?

下一篇: 更容易的方法使RegExp.test()对于空值返回false?