Regular Expressions in Javascript

Javascript provides three methods for leveraging the power of regexes into your code:

  • Constant regexes can be defined by wrapping the regex pattern in a pair of solidus, /, characters. It helps to think of this character pair as the regex equivalent of the single or double quote pair used to wrap Javascript strings. Constant regexes can be passed as arguments to search(), match() and replace() methods of the Javascript String object.
  • Alternately, you can define a constant regex and use Javascript RegExp object methods such as test() with it.
  • More extensive access to the power of regexes is provided through the methods and properties of the Javascript RegExp object. The regex pattern can be passed to the object as a parameter in its constructor. A pattern used by an existing RegExp object can be modified at any time by calling its compile method. Patterns passed to RegExp object methods should not be wrapped in a solidus pair.

Javascript uses a global RegExp object to perform operations involving regexes. After the operation has been successfully completed, the properties of this global object - such as leftContext, lastMatch etc contain the results of that operation. For instance, the code

functionTest()
{
varr = /Size X+L/;
r.test('Also in Size XL and Size XXL');
alert([RegExp.leftContext,RegExp.lastMatch,RegExp.rightContext]);
}

would display the message ""Also in ,Size XL, and Size XXL".

Regular Expression Sandbox
Model
Data

Do not wrap the model expression in a /.../ pair. The characters ^$.?*!+:=()[]{}|\\ must be escaped - except when then occur inside a character class. Invalid characters will be grayed out.
Result Left Text Match Right Text
       

Download
Jump To...

Colophon