Any sequence of characters that’s not a special RegEx character or operator represents a character literal.
var pattern = /test/;
RegEx literals are delimited using forward slashes.
var pattern = new RegExp("test");
Both of these formats result in the same RegEx being created in the variable pattern.
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