I just wanted to post a note here about the fact that there’s a couple of ways to run regexps in JS.
- Via the string itself: str.match(regexp)
- Via the regexp: regexp.exec(str)
Both of those methods of execution return the same thing (an array of stuff, I won’t bore with the details here).
But one way has a distinct advantage IMHO: If you run regexp.exec() it will call toString() on the str if it is an object that isn’t a string. This is more like the perl way of doing things. Whereas if you have an object that can stringify, you can’t call object.match() on it and expect it to work.
Also you don’t have to have a regexp object there – JS supports perl’s shorthand notation: /foo/i.exec(…)
The one thing that I find it staggering to believe that is missing though is any sort of quotemeta function. There’s no safe/secure way to create a regexp out of an external variable without rolling your own quotemeta(). That’s unbelievably dumb to me. I hope the ECMA guys realise this and put it into the RegExp object for the next major revision.