0

In JavaScript, RegEx objects can be instantiated with flags such as g for global matching and i for case-insensitive.

Intuitively, it makes sense for i to be a property of the constructed RegEx, because the RegEx engine is making a scanner where 'A' and 'a' count as the same token.

I can't come up with a similar argument for the g flag, however. For example, the following code replaces 'p' characters with 'd' characters (printing "addle"):

"apple".replace(/p/g, "d");

Since the RegEx only matches a single 'p', it has to match multiple times to replace all 'p's. Arguably, the RegEx shouldn't "know" that it will be used in this way and the code would be more semantic if it was allowed to be written as this instead:

"apple".replace(/p/, "d", true);

What is the advantage of JavaScript's way of doing things? Is it style/readability, or is there perhaps some optimization that this enables?

  • 2
    I think this just reflects historical interpretation of regular expression commands. – Erik Eidt May 19 '16 at 22:02
  • In Ruby, for example, there are two methods, sub and gsub. – Jörg W Mittag May 19 '16 at 22:18
2

Probably because that's how regular expression flags are handled in most text editors and other programming languages.

A lot of things about regular expressions make more sense when you're using them in a text editor such as vim, where almost all actions are keyboard-driven. For example, in vim if I type :s/foo/bar/g and press enter, all instances of foo will be replaced with bar. This is where the extreme terseness of regular expressions is a big win. Most of the time you're only typing out the regex once to get something done, and you don't have to worry about whether a coworker will have trouble making sense out of it tomorrow. In this context, implementing flags as single characters hanging off the end of the pattern makes perfect sense. Similar arguments apply to scripting languages when they're used for one-off throwaway code rather than industrial-strength enterprise codebases.

Javascript simply adopted the same regular expression syntax everyone else was using, so that everyone who was already familiar with some existing flavor of regular expressions could use Javascript's without much effort. If we were redesigning regular expessions from the ground up as a programming language feature rather than a text editor feature, we would probably handle flags very differently. Personally, I'd go with an options object rather than a "naked boolean".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.