Flags are basically just a set of options you can specify for your regular expression, which will control how it responds to various situations. I will quickly guide you through all of them, but first, let's have a look at how they are specified. Consider this example:
let regex = new RegExp("john"); let testString = "Hello, my name is John Doe!"; let hasMatch = regex.test(testString); alert("Has match: " + hasMatch);
I specify a very simple regular expression (in fact, it's so simple that we could do it without the regex part, but don't worry about that for now!) which will look for the word "john". I then test this against a string which clearly includes this popular name, but the result might surprise you, because the message will be:
Has match: false
Ignore case flag: i
With just a very small modification to the first line of the above example, we can make the regular expression completely ignore case, hence the name "ignore case", or simply just "i" when specified as a flag. Here's how it looks:
let regex = new RegExp("john", "i"); let testString = "Hello, my name is John Doe!"; let hasMatch = regex.test(testString); alert("Has match: " + hasMatch);
Now the result will be much more positive:
Has match: true
List of flags
Here's a complete list of the flags available. Some of them are pretty self-explanatory, while others are a bit more complicated, especially if they refer directly to the behavior of various regular expression operators. For now, they are mostly for reference - come back to them when you have a better understanding of regular expressions, because you will definitely need them at some point.
- g - Performs a global match - all matches will be found, instead of just the first.
- i - Ignore case (discussed above)
- m - Performs multiline matches. The behavior of the ^ and $ regex operators will change to reflect this.
- s - Allows the regex . (period) operator to match even newline characters.
- u - Enables Unicode support.
- y - Matches will be sticky, looking only at exact position in the text.
Using multiple flags
You can very easily specify multiple flags, if needed. For instance, you may need to perform a case-insensitive, multiline, global search, and that's not a problem - simply combine all three flags as the parameter, like this:
let regex = new RegExp("john", "gim");
Notice I have "gim" as the flags paramter (global, ignore case, multiline). The order of the flags doesn't matter.
Flags with literal regex notation
Flags can be specified if you use the literal notation for regular expressions to - they simply go after the last forward slash, like this:
let regex = /john/gim;
This regex will, just like the one above, match the word "john", using the global, ignore case, multiline flags.