spacer

Webref WebRef   Sitemap · Experts · Tools · Services · Newsletters · About i.com

home / experts / javascript / column5


JavaScript Regular Expressions

Developer News
Microsoft Shows Off Silverlight 4, IE9 Plans
Metasploit Expands Vulnerability Test Framework
HyperCard Reborn?

Defining a Regular Expression (JavaScript)

One way to define a regular expression is to simply assign it to a variable:

var varName = /PATTERN/[g|i|gi];

Here's an example:

var child = /(Bart|Lisa|Maggie) Simpson/i;

If you plan to use the regular expression only once, you can hand it in its literal form (/.../) to the desired method.

Note that the modifier (/g, /i, or /gi) is not required.

Another way to create a regular expression is to define it as an instance of the global RegExp object:

var varName = new RegExp("PATTERN", ["g"|"i"|"gi"]);

Once again, the modifiers are optional. Now, take a look at the same regular expression defined in another fashion:

var child = new RegExp("(Bart|Lisa|Maggie) Simpson", "i");

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 RegExp() constructor function provides runtime compilation of the regular expression. That is, the pattern is compiled just before use, or when the compile() method is invoked.

http://www.internet.com

internet.commediabistro.comJusttechjobs.comGraphics.com

Search:

WebMediaBrands Corporate Info

Legal Notices, Licensing, Permissions, Privacy Policy.
Advertise | Newsletters | Shopping | E-mail Offers | Freelance Jobs

webref The latest from WebReference.com Browse >
Rolling Out Your Own HTML Application Version Control · HTML 5: Client-side Storage · Working with Ajax Server Extensions
Sitemap · Experts · Tools · Services · Email a Colleague · Contact FREE Newsletters 
 The latest from internet.com
Wi-Fi Product Watch, November 2009 · Chip Market Recovering From '08 Collapse · Low-Cost Tools to Kickstart Your New Business

Created: October 23, 1997, 1997
Revised: December 4, 1997
URL: http://www.webreference.com/js/column5/define.html