Creating Regular Expressions in JavaScript

JavaScript FAQ | JavaScript Strings and RegExp FAQ  

Question: How do I create a regular expression?

Answer: To create a regular expression, you can use a regular expression literal or the RegExp constructor.

Regular expression literals in JavaScript use this syntax:

/elements/flags       or, without the optional flags, simply:
/elements/

The regular expression's elements specify what you would like to match or replace.
The flags specify whether the matching/replacing must be done in the case-insensitive (i) and/or global (g) and/or multiline (m) mode. You will find a more detailed discussion of the supported elements and flags on the Regular expression syntax page.

Examples of regular expression literals:

re = /^\s+|\s+$/g        // any number of leading/trailing whitespaces
re = /\d\d\d/            // one sequence of 3 digits (1st match only)
re = /\d\d\d/g           // any sequence of 3 digits 
re = /[0-9][0-9][0-9]/g  // any sequence of 3 digits 
re = /jan|feb|mar|apr/i  // Jan or Feb or Mar or Apr (case-insensitive)
re = /"[a-z]+"/gi        // any sequence of Latin letters, in quotes 

The RegExp constructor has this syntax:

new RegExp(elements,flags)
Examples of the RegExp constructor (the constructor calls below create regular expressions similar to the above):
//to get \s in regular expression, pass \\s to RegExp constructor!
re = new RegExp("^\\s*|\\s*$","g")
re = new RegExp("\\d\\d\\d",'')  
re = new RegExp("\\d\\d\\d",'g')                  
re = new RegExp("[0-9][0-9][0-9]","g")      
re = new RegExp("jan|feb|mar|apr","i") 
re = new RegExp('"[a-z]+"',"gi")   

Note that in order to pass quotes to the RegExp constructor as part of the elements string, the quotes should be preceded with a backslash - just like in JavaScript strings in general.

Copyright © 1999-2011, JavaScripter.net.