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.
Example:
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"); // trueA 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."
constructorRegExp objectglobalg flag was setignoreCasei flaglastIndexmultilinem flag was usedprototypesourceexec(text)test(text)true if the pattern matches the string or false otherwisetoString()RegExp objectvalueOf()RegExp objectIf 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-2011 Dive Into JavaScript