JavaScript compile()Method
JavaScript RegExp Object
Definition and Usage
The compile() method is used to compile a regular expression during script execution.
The compile() method can also be used to change and recompile a regular expression.
Syntax
RegExpObject.compile(regexp,modifier)
| Parameter | Description |
|---|---|
| regexp | A regular expression. |
| modifier | Specifies the type of matching. "g" for global matching, "i" for case-insensitive matching, "gi" for global case-insensitive matching. |
Browser Support
![]()
![]()
![]()
![]()
![]()
All browsers except Opera support the compile() method.
Example
Example
Globally search for "man" in a string and replace it with "person". Then use the compile() method to change the regular expression to replace "man" or "woman" with "person":
<script>
var str="Every man in the world! Every woman on earth!";
var patt=/man/g;
var str2=str.replace(patt,"person");
document.write(str2+"<br>");
patt=/(wo)?man/g;
patt.compile(patt);
str2=str.replace(patt,"person");
document.write(str2);
</script>
var str="Every man in the world! Every woman on earth!";
var patt=/man/g;
var str2=str.replace(patt,"person");
document.write(str2+"<br>");
patt=/(wo)?man/g;
patt.compile(patt);
str2=str.replace(patt,"person");
document.write(str2);
</script>
The output of the above example is:
Every person in the world! Every woperson on earth!
Every person in the world! Every person on earth!
Every person in the world! Every person on earth!
Try it yourself »
JavaScript RegExp Object Other Extensions