spacer

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

home / experts / javascript / column5


JavaScript Regular Expressions

Developer News
News Flash: Adobe Has iPhone Workaround
Adobe's Flash 10.1 Goes Mobile (Minus iPhone)
A Salute to Visionary CEOs

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, Reprints, Permissions, Privacy Policy.
Advertise | Newsletters | Shopping | E-mail Offers | Freelance Jobs

webref The latest from WebReference.com Browse >
Building a Banking Application Home Page with OOP · Mixing Scripting Languages · Review: phpFox, a Social Networking CMS with all the Bells and Whistles
Sitemap · Experts · Tools · Services · Email a Colleague · Contact FREE Newsletters 
 The latest from internet.com
Enterprise 2.0: Social Networking in the Cloud · BroadSoft Marketplace Hastens Pace of Telephony Innovation · Review: HTC Hero for Sprint

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