Regular Expressions Exact Match

Any sequence of characters that’s not a special RegEx character or operator represents a character literal.

For example, if we wanted to create a RegEx that matches the string test exactly, in JavaScript we could use the following RegEx literal:

var pattern = /test/;

RegEx literals are delimited using forward slashes.

In JavaScript, alternatively, we could construct a RegExp instance, passing the RegEx as a string:

var pattern = new RegExp("test");

Both of these formats result in the same RegEx being created in the variable pattern.

JavaScript Flags

The following flags are appended to the end of the literal (for example, /test/ig) or passed in a string as the second parameter to the RegExp constructor (new RegExp(“test”,”ig”)).

  • i: This makes the RegEx case-insensitive, so /test/i matches not only test, but also Test, TEST, tEsT, and so on.
  • g: This matches all the instances of the pattern as opposed to the default of local, which matches the first occurrence only.
  • m: This allows matches across multiple lines that might be obtained from the value of a textarea element.

The following example illustrates the various flags and how they affect the pattern match:

var pattern = /orange/;
console.log(pattern.test("orange")); // true
var patternIgnoreCase = /orange/i;
console.log(patternIgnoreCase.test("Orange")); // true
var patternGlobal = /orange/ig;
console.log(patternGlobal.test("Orange Juice")); // true

Leave a comment

Your email address will not be published. Required fields are marked *