1
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.)?

Community
  • 1
  • 1
user2901933
  • 149
  • 3
  • 9
  • How about e. g. `/,/.test([,,,]) === true` when the argument is not null but not a string? – le_m Jun 23 '16 at 21:13

3 Answers3

6

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.

Barmar
  • 741,623
  • 53
  • 500
  • 612
3

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

This is standard behavior in JavaScript. E. g. "null".replace(null, {}) === "[object Object]".

Follow Check if a variable is a string to check whether or not the argument is a string:

if (typeof myVar === 'string' || myVar instanceof String) { ... }
else return false;
Community
  • 1
  • 1
le_m
  • 19,302
  • 9
  • 64
  • 74
0

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
Zohaib Ijaz
  • 21,926
  • 7
  • 38
  • 60