Flags

This lesson will teach you about another component of regular expressions: flags.

We'll cover the following

Let’s quickly look at this topic before closing the chapter. Flags are the last bit of dynamic behavior we can add to our regular expressions. We mentioned them before, but we want to cover the full list of options here so you can have a full reference to check in the future.

Flags with descriptions and examples

As we mentioned, flags essentially allow you to change the way the RegExp parser understands your expressions. Here are their effects:

Flag Description Example
g Global match: This is the most common and the one we’ve been using all along. This flag makes sure you’re matching all occurrences of your pattern inside your string. Skipping this flag will stop matching once the first match is found. /a/g will match all instances of the letter “a” inside “have you had a real meal yet?”

While /a/ will only match the first one.
i Ignore case: This is yet another very relevant flag. Ignoring case will make sure characters aren’t matched by taking into account their case (i.e., a == A if you’re ignoring case). This is helpful when writing character classes because if you use ignore case, you’re writing good [a-z], but if you’re not, then you need to remember to add the uppercase variation: [a-zA-Z]. /a/gi will match all instances of the letter “a” inside “HAVE you had a REAL meal yet?”

Whilst /a/g will only match the lowercase occurrences: “HAVE you had a REAL meal yet?”
m Multi-line matching: This flag affects the behavior when you’re using the positional quantifiers, ^ and $, because those two start taking into account newline characters. So, instead of meaning “at the start” and “at the end” of the string, they mean: “at the start” or “at the end” of each line. /^(line)$/g will not capture anything in the following string:
“line
line
line.”

While /^(line)$/gm will return three different matches.
s This flag allows the dot wildcard to also match new lines. Remember that by default the dot wildcard matches everything but new lines. /line1.line2/g will not match anything in the following string:

“line1
line2.”

While /line1.line2/gs will, in fact, match the full string.
u The Unicode flag allows you to match Unicode characters correctly. This is because extended characters use more bytes than normal. ASCII characters and your RegExp parser will not understand your Unicode unless you specify the correct flag. So, if you want to match emojis, for example, remember to use this flag! /[𝒳𝒴]/u will match correctly against the '𝒳' string.
y The sticky mode flag will let you perform sequenced searches on your string. Instead of starting from the beginning of the string every time you search, it allows you to start each one at the last match position. We’ll cover examples for this use case in the next chapter, so keep reading!

Get hands-on with 1400+ tech skills courses.