0

I have this JavaScript row:

var matcherName = new RegExp(filterValueName);

The filterValueName variable has some string but, might be situation when filterValueName is undifined .

My question is how can I know if matcherName was constructed by filterValueName = undifined?

Michael
  • 13,950
  • 57
  • 145
  • 288

3 Answers3

2

Why not testing filterValueName first? Something like

var matcherName = null;
if( filterValueName != undefined ) {
  var matcherName = new RegExp(filterValueName);
}
...
if( matcherName === null ) {
  // filterValueName was undefined
} else {
  // filterValueName was ok
}
RiccardoC
  • 876
  • 5
  • 10
0

In Firefox and Chrome at least the regex defaults to /(?:)/. But just compare the strings to be sure:

function is_regex_undefined(regex) {
    var undefined;
    return String(regex) === String(new RegExp(undefined));
}

According to MDN the pattern should not be absent. I would not doubt that there might be a JS engine where new RegExp(undefined) equals /undefined/. Then this solution would fail if you really have an expression that should match the string "undefined". @RiccardoC's answer is the safer choice.

Community
  • 1
  • 1
Kijewski
  • 25,517
  • 12
  • 101
  • 143
0

I would recommend having an if statement before, since you can't easily extract what you constructed it with. Is there anything preventing you from testing the values before you work with them?

var matcherName = new RegExp("foo");
var matcherName2 = new RegExp(undefined);
console.log(matcherName)
VM522:2 /foo/
console.log(matcherName2)
VM527:2 /(?:)/