RegExp, object of regular expression in JavaScript

The RepExp object is declared with a regular expression and its methods are applied to a content, either to check that the text matches the definition, or to extract parts of the text.

Methods defined in the RepExp object may be involved with the instance or directly with a literal.

The parameter of the contructor is a regular expression mask

The RegExp constructor has two possible parameters, the regular expression in the form of string, and the modifier which is optional.

var x = new RegExp("expression" [, "modifier"])

The modifier is a letter or combination of "i", "g", "m" letters.

The variable x is an instance of RegExp to which may be associated methods, and that can also be a parameter for some String functions.

The object is used by applying its methods to a content

Once the instance of the object created, a method is associated to it, with for parameter the content that you want to parse with the regular expression.

var result = x.test("text");

An object can also be used as a parameter of some methods of the String object, including search, replace, match.

Example:

var s = new String("hello");
var re = new RegExp("(o)+");
document.write(s.search(re));

Returns and displays the number 4, because "o" is in position 4 from zero.

Properties of the object

An instance of the object have several properties assigned by default or by a modifier.

global
By default, only the first match, you can take into account all occurrences with the modifier "g".
ignoreCase
By default differentiates lowercase and uppercase. The modifier "i" allows to ignore the difference.
multiline
By default addresses only the first line in a text made of several line separated by the end of line code. The modifier "m" is for handling all the lines.
lastIndex
The attribute lastIndex points out the position where must begin the next test.
$1 .. $9
The internal variables $1 to $9 store the results of search and are equivalent to elements of the array returned by the method exec: $1 = x[0], $2 = x[1], and so on.
Methods of RegExp

The built-in regular expression applied to a content is used to test if it matches the definition, or to extract parts.

test
Compare the text with the expression and returns true if it matches, false otherwise.
For example, the expression "(a)+" defines a pattern that say that the text should contain the letter a. If it is the case, returns true.
exec
Returns parts of a text as defined by the regular expression.
The return value is an array.

In combination with the object String, it is possible to add functions to this list as we saw with the previous example (search method).

See also

© 2008-2012 Xul.fr