RegExp Definition and Modifiers- Tutorial
RegExp Definition and Modifiers: Overview
var patt=new RegExp (pattern,modifiers);
The first option above creates a RegExp object literal that provides compilation of the regular expression when the script is loaded. You will find this will give better performance when you know the regular expression is going to remain constant.
The second option above creates a RegExp object using a constructor function. This option compiles the regular expression in runtime. This means that if you know the regular expression will change or you do not know the pattern, due to user input, this is the preferred method for RegExp object creation.
There are three basic modifiers, or flags, for RegExp, they are i, g, m. The i modifier is used when you want to perform a case-insensitive search. Case-insensitive means search all words and ignoring the capitalization of letters. The g modifier is used when searching “globally” in your code. This means it continues to search for a match after the first match is made and returns all matches in your code. The g modifier will only search for the expression you enter and is case sensitive. If you enter the expression var patt1=/or/g;, it will return matches containing “or”. For example, the word “or” would be chosen and the word “selector” would be chosen, as it contains the pattern “or”. You can also combine the modifiers to perform a global, case-insensitive search by using gi.
The m flag, or modifier, is called the multiline flag. It is used to match the beginning (^) or end ($) of each line, delimited by \n (new line character) or \r (carriage return character), not only the very beginning or end of the input string as a whole. The m modifier stops after the first match and is case sensitive. To perform a global, case insensitive search, combine m with the g and i modifiers.
RegExp Definition and Modifiers: Syntax Examples
The following examples show a global, case insensitive search and a multiline search.
RegExp Definition and Modifiers: General Syntax
Type: var a=/b/c;
var a=new RegExp (b.c);
Where “a” is the name of the regular expression you wish to create, “b” is the pattern to be searched for, and “c” are the modifiers g or i, or both.
RegExp Definition and Modifiers: Video Lesson