Javascript Regular Expressions








RegExp type stores regular expressions in Javascript.

Regular expressions in Javascript has the following syntax.

var expression = /pattern/flags;

The pattern can be any simple or complicated regular expression. It can include.

  • character classes
  • quantifiers
  • grouping
  • lookaheads
  • backreferences.




mode

Each regular expression can have three matching modes.

  • g - global mode, the pattern will be applied to entire string instead of stopping after the first match.
  • i - case-insensitive mode, the case of the pattern and the string are ignored.
  • m - multiline mode, the pattern will continue to match after reaching the end of one line of text.
var text = "cat, bat, sat, fat, at, hat, gate, create";
// Match all instances of "at" in a string.
var pattern1 = /at/g;
var matches = pattern1.exec(text);
console.log(matches);

//Match the first instance of "bat" or "cat", regardless of case.
var pattern2 = /[bc]at/i;
matches = pattern2.exec(text);
console.log(matches);

// Match all three-character combinations ending with "at", regardless of case.
var pattern3 = /.at/gi;
matches = pattern3.exec(text);
console.log(matches);




Escape

We have to escape all metacharacters by using \ when using them as part of the pattern.

The metacharacters are as follows:. ( [ { \ ^ $ | ) ] } ? * + .


// Match the first instance of "bat" or "cat", regardless of case.
var pattern1 = /[bc]at/i;
/* w  w w.jav  a 2 s.com*/
// Match the first instance of "[bc]at", regardless of case.
var pattern2 = /\[bc\]at/i;

// Match all three-character combinations ending with "at", regardless of case.
var pattern3 = /.at/gi;

// Match all instances of ".at", regardless of case.
var pattern4 = /\.at/gi;