Javascript: what's the point of RegExp.compile()?

Solution 1:

The RegExp().compile() method is deprecated. It's basically the same as the constructor, which I assume is why it was deprecated. You should only have to use the constructor nowadays.

In other words, you used to be able to do this:

var regexp = new RegExp("pattern");
regexp.compile("new pattern");

But nowadays it is not any different from simply calling:

var regexp = new RegExp("pattern");
regexp = new RegExp("new pattern");

Solution 2:

And with Opera 11, running RegExp.compile() will actually cause errors.

Evidently, when Opera "compiles" a regex, it wraps the re.source string in forward slashes (e.g. re.source == "^(.)" becomes "/^(.)/"). If you manually compile the regex, Opera doesn't recognize this fact and goes ahead and compiles it again (re.source becomes "//^(.)//"). Each compile results in an extra set of forward slashes, which changes the meaning of the regular expression and results in errors.