The JavaScript RegExp Object

Regular expressions are an integral part of JavaScript. The RegExp object offers all the necessary methods to test and match regular expression patterns against strings of characters.

In JavaScript, regular expressions are a built-in data type. The RegExp object is a wrapper for the regular expression primitive.

Regular expressions are built directly into the syntax. As a result, regular expression primitives have access to properties and methods of the RegExp object. The conversion between regular expression primitives and RegExp objects is done automatically by the JavaScript engine.

A regular expression object can be created using the new RegExp() constructor:

var re1 = new RegExp(pattern [, flags]);

The pattern argument represents the regular expression patter, while the flags argument is a sequence of modifiers.


var re_match_positive = new RegExp("^[1-9]\d*$");

This creates a regular expression object that can be used to test if a given value is a positive integer:

re_match_positive.test("1"); // true
re_match_positive.test("foo"); // false
re_match_positive.test("0"); // false
re_match_positive.test("123"); // true

A regular expression primitive can be created using the literal notation:

var re2 = /pattern/flags;

The arguments are treated the same way. For example:

var re_ltrim = /^\s+/;
var re_rtrim = /\s+$/;

These are two regular expressions that can be used to strip whitespace from the beginning and end of a string:

var test_str = " We're all mad here. I'm mad. You're mad. ";
test_str.replace(re_ltrim, ""); // "We're all mad here. I'm mad. You're mad. "
test_str.replace(re_rtrim, ""); // " We're all mad here. I'm mad. You're mad."

RegExp Properties

Returns a reference to the function that created the RegExp object
The value of this property is true if the regular expression g flag was set
This property is true if the regular expression was compiled with the i flag
Indicates the index position of the last match
The value of multiline is true if the m flag was used
Allows the addition of properties and methods to all objects
The text pattern of the regular expression

RegExp Methods

Executes the specified pattern on the input string and returns an array of matched strings
Tests for a match in the input string and returns true if the pattern matches the string or false otherwise
Returns a string representation of the RegExp object
Returns the primitive value of the RegExp object

See also

If you see a typo, want to make a suggestion or have anything in particular you'd like to know more about, please drop us an e-mail at hello at diveintojavascript dot com.

Copyright © 2010-2013 Dive Into JavaScript