Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 476
Vilx- Avatar asked May 19 '09 20:05

Vilx-


People also ask

What is the use of compile () method in regex?

compile() method is used to compile a regular expression pattern provided as a string into a regex pattern object ( re. Pattern ). Later we can use this pattern object to search for a match inside different target strings using regex methods such as a re. match() or re.search() .

What is the purpose of RegExp method test ()?

JavaScript RegExp test() The test() method tests for a match in a string. If it finds a match, it returns true, otherwise it returns false.

What does RegExp do in JavaScript?

RegExp Object A regular expression is a pattern of characters. The pattern is used to do pattern-matching "search-and-replace" functions on text. In JavaScript, a RegExp Object is a pattern with Properties and Methods.

What is the use of RegExp?

Regular expressions are particularly useful for defining filters. Regular expressions contain a series of characters that define a pattern of text to be matched—to make a filter more specialized, or general. For example, the regular expression ^AL[.]* searches for all items beginning with AL.


1 Answers

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"); 
like image 101
Dan Lew Avatar answered Oct 01 '22 12:10

Dan Lew