0

I cannot figure out a way to detect if a variable is a regex. But I also need to figure out if it is an object so I cannot use the typeof(regex) === 'object' and rely on it since it may since the if statement will execute it as if it was a regex. But I would like it to work in legacy browsers too. Any help will be most appreciated.

var regex= /^[a-z]+$/;

//...Some code that could alter the regex variable to become an object variable.



if (typeof(regex) === 'object') {
    console.log(true);
}
Peter
  • 145
  • 2
  • 2
  • 9

2 Answers2

0

You can use instanceOf

var regex= /^[a-z]+$/;

//...Some code that could alter the regex variable to become an object variable.



if (regex instanceof RegExp) {
    console.log(true);
}
bluetoft
  • 5,373
  • 2
  • 23
  • 26
0

There are ways to do this, they include :

var regex= /^[a-z]+$/;

// constructor name, a string
// Doesn't work in IE
console.log(regex.constructor.name === "RegExp"); // true
// instanceof, a boolean
console.log(regex instanceof RegExp); // true
// constructor, a constructor
console.log(regex.constructor == RegExp); // true
DjaouadNM
  • 22,013
  • 4
  • 33
  • 55