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.
Each regular expression can have three matching modes.
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);
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;