Wednesday, November 24, 2010

JavaScript Snippet: Test Whether a JavaScript Variable is Regular Expression

Here is a short snippet if you ever need to check whether a JavaScript variable is regular expression.

function isRegExp(obj) {
   return === '[object RegExp]';

You might be wondering why on the earth you ever need this function. It could be when you want to develop a validation framework that takes a variable for validation purpose, and you want to make the validation framework flexible as flexible as possible, so that the variable could be a function, string or even a regular expression. Your validation framework would do different thing based on the type of the validation variable that is passed to the framework. Hope this makes sense to you now, maybe you have a totally different reason for using it, which is absolutely up to you... :-)

[UPDATE - Dec 10, 2010]: A couple of hours after I published the original blog post, I figured that I should be able to use JavaScript instanceof operator to achieve the same purpose, which could be an easier solution. But further reading indicated that will not work correctly if you are evaluating a cross-frame RegExp object. If you are interested, you may continue reading a very detailed explanation with regard to a similar testing of JavaScript Array object. I have also updated my code a little bit so it looks pretty much the same as kangax's isArray function now, shamelessly. ^_^

A lesson learned from this is, you should only trust JavaScript instanceof operator if your code never has the need to go cross frames. If you want a robust solution to evaluate the type of a JavaScript object, you better take the similar approach as I have just illustrated you.

You can always expect some surprise from JavaScript. Stay tuned until next time.

No comments:

Post a Comment