There are three methods used by a RegExp instance. They are:

  • exec();
  • test();
  • compile().

The exec() method is the most often used method. It accepts only one argument and it is used to extract groups of matched data from an expression and stores them as arrays. If no matched data is found the return value will be NULL. For instance the following example will return two matches from the given expression:

var text = "a+b+c";

var pattern = /(a+b(+c)?)?/gi;

var match = pattern.exec(text);

alert(match.input); //a+b+c

alert(match[0]);  //a+b+c

alert(match[1]);  // +c

In the example above, the modifier g must to be included or otherwise each call for match would return the same result.

The test() method is also used very often, especially in forms validations. This method accepts one argument and it is used to return true if the pattern matches the argument or false if it doesn't.

Consider the following example:

var text = "abc";

var pattern = /\d/;

alert(pattern.test(text)); //false

As seen above the text contains letters "abc" while the pattern is looking for a number; the result is false.

The compile() method may be used to modify (compile) a regular expression during script execution. This method accepts two arguments, a regular expression and a modifier (if wanted). The following example shows how it actually works:

var text="I am very tall person";

var pattern = /tall/g;

alert(pattern.test(text)); // true ("tall" found)

pattern.compile("short", "g");

alert(pattern.test(text)); // false ("short" not found)


Example of a basic usage of RegExp methods in JavaScript:


›› go to examples ››