Archive | July, 2010

Testing for RegExp

25 Jul
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.