Regular Expressions Exact Match


This entry is part 3 of 5 in the series Regular Expressions

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

JavaScript

For example, if we wanted to create a RegEx that matches the string test exactly, in JavaScript we could use the following RegEx literal as shown below. Of course we could substitute test with any string we wanted to use provided that we are not using any special characters. RegEx literals are delimited using forward slashes.

var pattern = /test/;

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
Series Navigation<< Regular Expressions IntroductionRegular Expressions Examples >>