Search code examples
javascriptregexnode.jsv8

How do you check if an object is a regular expression across V8 contexts?


I recently discovered that when you use the literal regular expression syntax in one V8 context, instanceof RegExp returns false even if you share the global RegExp object between contexts.

var Contextify = require('contextify');
var ctx = Contextify({ RegExp:RegExp, app: anExpressApp });

// When you create a new route, Express checks if the argument is an
// `instanceof RegExp`, and assumes it is a string if not.

ctx.run("
    app.get(new RegExp('...'), function() { ... }); // works because we share the `RegExp` global between contexts
    app.get(/.../, function() { ... }); // does not work
");

How do you reliably check if an object is a RegExp cross-context?


Solution

  • It looks like this suggestion gives us the most reliable route.

    if (Object.prototype.toString.call(regExp) == '[object RegExp]') ...
    

    This relies on the specified behavior of toString, which is to return the JavaScript internal [[Class]] property of the object (plus "[object " and "]").

    Since this is simple string comparison, it works across contexts.