home / experts / javascript / column5 |
|
Defining a Regular Expression (JavaScript)One way to define a regular expression is to simply assign it to a variable:
Here's an example:
If you plan to use the regular expression only once, you can hand it in its literal form ( Note that the modifier ( Another way to create a regular expression is to define it as an instance of the global
Once again, the modifiers are optional. Now, take a look at the same regular expression defined in another fashion:
Notice that the regular expression and the modifier(s) are enclose in quotes rather than forward-slashes. You should use the first syntax (literal notation) when you know the search string ahead of time, because literal notation provides compilation of the regular expression only once, when the script is first loaded. Use the other syntax (the constructor function) when the search string is changing frequently, or is unknown, such as strings taken from user input. The |
| ||||||||||||||||||||
Created: October 23, 1997, 1997
Revised: December 4, 1997
URL: http://www.webreference.com/js/column5/define.html