Uncategorized

On Javascript Regexp Matching

Javascript has built-in regular expressions, which is nice, though they are majorly lacking features from a modern regular expression library.

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.

Standard

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s