Javascript RegExp Object








RegExp constructor

Regular expressions can be created by using the RegExp constructor, which accepts two arguments:

  • a string pattern to match and
  • an optional string of flags to apply.

// Match the first instance of "bat" or "cat", regardless of case.
var pattern1 = /at/i;

// Same as pattern1, using the constructor.
var pattern2 = new RegExp("at", "i");

Double-escape are needed for RegExp constructor since it accepts string as parameter.

The following table compares patterns in literal form and cooresponding form in the RegExp constructor.

LITERAL PATTERNSTRING EQUIVALENT
/\[ab\]at/"\\[ab\\]at"
/\.ab/"\\.ab"
/name\/age/"name\\/age"
/\d.\d{1,2}/"\\d.\\d{1,2}"
/\w\\hello\\456/"\\w\\\\hello\\\\456"




RegExp exec()

RegExp exec() accepts the target string, and returns an array of information about the first match or null if no match was found.

The returned array is an instance of Array with two additional properties:

  • index, which is the location in the string where the pattern was matched
  • input, which is the string that the expression was run against

The first item in the array is the string that matches the entire pattern.

Any additional items represent captured groups. In case of no capturing groups, the array has only one item.


var text = "this is a test";
var pattern = /is/gi;

var matches = pattern.exec(text);
console.log(matches.index);
console.log(matches.input);
console.log(matches[0]);
console.log(matches[1]);
console.log(matches[2]);

The code above generates the following result.





Note

exec() returns one match at a time even for global pattern.

Without the global flag, calling exec() on the same string multiple times returns information about the first match.

With the g flag, each call to exec() moves to the next matches.


var text = "cat, bat, sat, fat, hat, gate,ate.appropriate";
var pattern1 = /.at/;
//from  www  . j  a v  a2 s .c  om
var matches = pattern1.exec(text);
console.log(matches.index);        
console.log(matches[0]);           
console.log(pattern1.lastIndex);   

matches = pattern1.exec(text);
console.log(matches.index);        
console.log(matches[0]);           
console.log(pattern1.lastIndex);   

var pattern2 = /.at/g;
var matches = pattern2.exec(text);

console.log(matches.index);        
console.log(matches[0]);           
console.log(pattern2.lastIndex);   

matches = pattern2.exec(text);
console.log(matches.index);        
console.log(matches[0]);           
console.log(pattern2.lastIndex);   

matches = pattern2.exec(text);
console.log(matches.index);        
console.log(matches[0]);           
console.log(pattern2.lastIndex);   

matches = pattern2.exec(text);
console.log(matches.index);        
console.log(matches[0]);           
console.log(pattern2.lastIndex);   

The code above generates the following result.

RegExp Instance Properties

RegExp type has the following properties:

  • global - A Boolean value tells if the g flag has been set.
  • ignoreCase - A Boolean value tells if the i flag has been set.
  • lastIndex - the character position where the next match will be attempted. This value begins as 0.
  • multiline - A Boolean value indicating whether the m flag has been set.
  • source - The string source of the regular expression without opening and closing slashes.

var pattern1 = /\[bh\]at/i;
console.log(pattern1.global);     //false
console.log(pattern1.ignoreCase); //true
console.log(pattern1.multiline);  //false
console.log(pattern1.lastIndex);  //0
console.log(pattern1.source);     
//w  w w. java  2 s.com
var pattern2 = new RegExp("\\[bh\\]at", "i");

console.log(pattern2.global);     //false
console.log(pattern2.ignoreCase); //true
console.log(pattern2.multiline);  //false
console.log(pattern2.lastIndex);  //0
console.log(pattern2.source);     

The code above generates the following result.

RegExp Properties

RegExp type has several properties telling information about the last regular-expression operation.

These properties have two forms:a verbose property name or a shorthand name.

  • Verbose Name:input
    Short Name: $_
    The last string matched against. The input property contains the original string.
  • Verbose Name: lastMatch
    Short Name: $&
    The last matched text. The lastMatch property contains the last string that matches the entire regular expression.
  • Verbose Name:lastParen
    Short Name:$+
    The last matched capturing group. The lastParen property contains the last matched capturing group.
  • Verbose Name: leftContext
    Short Name: $`
    The text that appears in the input string prior to lastMatch. The leftContext property contains the characters of the string before the match.
  • Verbose Name: multiline
    Short Name: $*
    A Boolean value specifying whether all expressions should use multiline mode.
  • Verbose Name: rightContext
    Short Name:$'
    The text that appears in the input string after lastMatch. The rightContext property contains the characters after the match.

These properties can be used to extract specific information about the operation performed by exec() or test(). Consider this example:


var text = "cat,hat,";
var pattern = /at/g;
/* w  w w  . j  ava 2 s.com*/
if (pattern.test(text)){
   console.log(RegExp.input);
   console.log(RegExp.leftContext);
   console.log(RegExp.rightContext);
   console.log(RegExp.lastMatch);
   console.log(RegExp.lastParen);
   console.log(RegExp.multiline);

   console.log(RegExp.$_);
   console.log(RegExp["$`"]);
   console.log(RegExp["$'"]);
   console.log(RegExp["$&"]);
   console.log(RegExp["$+"]);
   console.log(RegExp["$*"]);

}

The code above generates the following result.

RegExp.$1 .. RegExp.$9

RegExp.$1 through RegExp.$9 store up to nine capturing-group matches. These properties are filled in when calling either exec() or test().


var text = "cat,hat,bat,";
var pattern = /at/g;

if (pattern.test(text)){
   console.log(RegExp.$1);
   console.log(RegExp.$2);
   console.log(RegExp.$3);
}

RegExp test() method

test() accepts a string and returns true if the pattern matches the argument and false if it does not.

The test() method is often used in if statements, such as the following:


var text = "000-00-0000";
var pattern = /\d{3}-\d{2}-\d{4}/;

if (pattern.test(text)){
    console.log("The pattern was matched.");
}

The code above generates the following result.

RegExp's toLocaleString() and toString()

toLocaleString() and toString() return the literal representation of the regular expression.


var pattern = new RegExp("\\[oo\\]at", "gi"); 
console.log(pattern.toString()); // /\[oo\]at/gi 
console.log(pattern.toLocaleString()); // /\[oo\]at/gi 

The valueOf() method for a regular expression returns the regular expression itself.

The code above generates the following result.