METHOD:  RegExp::compile


object.compile(pattern[, flags])
 
This method compiles a regular expression object during execution of a script. It is used with a RegExp object created with the constructor function in order to compile it once only, this avoiding repeated compilation of a regular expression. This can be done once a regular expression has been got and you are sure that it will then remain constant throughout the rest of the script. The compile method can also be used to change and recompile a regular expression.
 
For example, suppose you created a regular expression consisting of the letters 'man' and then searched for a match in a string and replaced it with 'person' thus:
 
Code:
myRegExp = /man/
myString = "The Chairman of the Board"
newString = myString.replace(myRegExp, "person")

 
...the code would match the 'man' of 'Chairman' and replace it producing the word 'Chairperson'. If then you wanted to change the regular expression in order to replace either 'man' or 'woman' with 'person', you could do so using the compile method thus:
 
Code:
myRegExp.compile("(wo)?man")
newString = myString.replace(myRegExp, "person")

 
The compile method can also be used with the flags 'g' for a global match, 'i' for a case-insensitive match and 'gi' for a global, case-insensitive match. So, to expand on the above example, you could alter the regular expression 'MyRegExp' to search for all occurrences of the substrings 'man' and 'woman' and replace them with 'person' as follows:
 
Code:
myRegExp.compile("(wo)?man", "g")
newString = myString.replace(myRegExp, "person")

 
NOTE:
 
Calling the compile method alters the value of the source, global and ignoreCase properties of a regular expression.


Copyright 1999-2001 by Infinite Software Solutions, Inc. All rights reserved.
Trademark Information