Regular Expressions - Modifiers (Flags)
Flags, also known as modifiers, are used in regular expressions to specify additional matching strategies.
Flags are not written inside the regular expression; they are located outside the expression in the following format:
/pattern/flags
The table below lists commonly used modifiers in regular expressions:
Modifier | Meaning | Description |
---|---|---|
i | ignore - case insensitive | Makes the match case-insensitive; searches without distinguishing between uppercase and lowercase: A and a are treated the same. |
g | global - global match | Finds all matches. |
m | multi line - multi-line match | Makes the boundary characters ^ and $ match the beginning and end of each line, rather than the beginning and end of the entire string. |
s | dotall - dot includes newline | By default, the dot . matches any character except a newline \n. With the s modifier, the dot . includes the newline \n. |
g Modifier
The g modifier finds all matches in the string:
Example
Searching for "tutorialpro" in a string:
var str="Google tutorialpro taobao tutorialpro";
var n1=str.match(/tutorialpro/); // Finds the first match
var n2=str.match(/tutorialpro/g); // Finds all matches
i Modifier
The i modifier enables case-insensitive matching. Here is an example:
Example
Searching for "tutorialpro" in a string:
var str="Google tutorialpro taobao tutorialpro";
var n1=str.match(/tutorialpro/g); // Case-sensitive
var n2=str.match(/tutorialpro/gi); // Case-insensitive
m Modifier
The m modifier allows ^
and $
to match the start and end of each line in a text block.
Without m, g matches only the first line; with m, it matches across multiple lines.
Here is an example using \n
for line breaks:
Example
Searching for "tutorialpro" in a string:
var str="tutorialprogoogle\ntaobao\ntutorialproweibo";
var n1=str.match(/^tutorialpro/g); // Matches one occurrence
var n2=str.match(/^tutorialpro/gm); // Matches across multiple lines
s Modifier
By default, the dot .
matches any character except a newline \n
. With the s modifier, the dot .
includes the newline \n
.
Here is an example of the s modifier:
Example
Searching in a string:
var str="google\ntutorialpro\ntaobao";
var n1=str.match(/google./); // Without s, does not match \n
var n2=str.match(/tutorialpro./s); // With s, matches \n