Vilx-
Vilx-

Reputation: 106902

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

I've got a situation where I want to get a regexp from the user and run it against a few thousand input strings. In the manual I found that the RegExp object has a .compile() method which is used to speed things up ins such cases. But why do I have to pass the regexp string to it again if I already passed them in the constructor? Perhaps constructor does the compile() itself?

Upvotes: 64

Views: 32307

Answers (4)

loretoparisi
loretoparisi

Reputation: 16271

You have to compile your regex first to use it if you are using /, try this out:

var regex=new RegExp('/[a-zA-Z]/')

console.log("not compiled with escape /", regex.test("ciao") )

regex.compile()

console.log("compiled", regex.test("ciao") )

var regex=new RegExp('[a-zA-Z]')

console.log("not compiled, but no escape /", regex.test("ciao") )

Upvotes: 6

Dan Lew
Dan Lew

Reputation: 87420

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");

Upvotes: 104

ridgerunner
ridgerunner

Reputation: 34385

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.

Upvotes: 7

olliej
olliej

Reputation: 36763

As far as i can tell all RegExp.compile does is replace the underlying regular expression of a RegExp object. I think compile may have had value in the past, but all modern JS engines "compile" the regex on first call and cache that "compiled" version.

Upvotes: 4

Related Questions