Mahemoff's Software As She's Developed [Mini Edition]

Mahemoff's Software As She's Developed [Mini Edition]

Michael Mahemoff  //  Web designer/developer. Rails/Ajax/etc

This is my random anything-goes blog - I am treating it as an easy way to generate mini web pages, rather than a continuous flow of consciousness on any particular topic. It gives me an outlet for things I can't say on Twitter in 140 characters, but are too unstructured, short, incomplete, and grammatically trainwrecked to post on my main blog at http://softwareas.com.

Jul 25 / 2:01am

Testing for RegExp

This seems to have escaped the attention of the internets, but typeof(/xyz/) weirdly returns "object" on Webkit or "function" on Firefox. (@bcherry explains RegExp *is* a function in Webkit - /foo/("foo") ). Not "regexp" as I'd hoped. So how to detect a regexp?

function isRegExp(o) {
  return typeof(o.compile) === "function"
      && typeof(o.exec) === "function"
      && typeof(o.test) === "function";
}

Thankyou @ilinsky for pointing out the much simpler:
/xyz/ instanceof RegExp

If you're wondering why I need this, it's for a multi-argument function, and I want to allow caller to pass the args in any order, using type inference to determine which argument is which. (Like jQuery does, e.g. with $.ajax().) One of the possible arguments is a regexp.

0 comments

Leave a comment...