[Prev: Size] [Home] [Next: String]

RegExp

A RegExp is a regular expression matcher for strings.

Regular expressions can be created either by using the /expression/ syntax or by using the RegExp constructor as shown below. Note that when using the RegExp constructor, a string is passed, and all backslashes have to be escaped using an extra backslash, i.e \d. Below are two ways to create regular expressions that matche a pattern of two digits followed by a color and then two digits again, e.g. 17:42.

    var direct = /(\d\d):(\d\d)/
    var indirect = new RegExp( "(\\d\\d):(\\d\\d)" );
RegExp Properties
valid

Returns true if the regular expression has a valid syntax; otherwise false.

empty

Returns true if the pattern is empty; otherwise false.

matchedLength

Contains the length of the last matched string, or -1 if there was no match.

capturedTexts

Contains an array of all the captured texts from the previous match.

RegExp Functions
toString()

toString()

Returns the regular expression pattern as a string.

search()

search( text )

    var re = /\d* cm/; // matches 0 or more numbers followed by 'cm'
    re.search( "A meter is 100 cm long" ); // returns 11

Searches text for the pattern defined by the regular expression. The function returns the position in the text of the first match or -1 if no match is found.

searchRev

searchRev( text )

Same as search(), but searchRev searches from the end of the text.

exactMatch

exactMatch( text )

Returns true if text exactly matches the pattern in this regular expresssion; otherwise false.

cap

cap( nth )

    re = /name: ([a-zA-Z ]*)/;
    re.search( "name: John Doe, age: 42" );
    re.cap(0);  // returns "name: John Doe"
    re.cap(1);  // returns "John Doe"
    re.cap(2);  // returns undefined, no more captures.

Returns the nth capture of the pattern in the previously matched text. The first captured string (cap(0) ) is the part of the string that matches the pattern if there is a match. The following captured strings are the parts of the pattern enclosed by parenthesis. In the example above we try to capture ([a-zA-Z ]*), which will capture all letters and spaces after the name: part of the string.

pos

pos( nth )

    re = /name: ([a-zA-Z ]*)/;
    re.search( "name: John Doe, age: 42" );
    re.pos(0); // returns 0, position of "name: John Doe"
    re.pos(1); // returns 6, position of "John Doe"
    re.pos(2); // returns -1, no more captures

Returns the position of the nth captured text in the search string.

[Prev: Size] [Home] [Next: String]