RegExp flags in JavaScript are modifiers that change how a regular expression behaves during pattern matching. Flags control things like case sensitivity, global matching, multi-line behavior, Unicode handling, and sticky matching. Understanding RegExp flags helps in writing accurate and flexible text search patterns.
What Are RegExp Flags in JavaScript?
RegExp flags are added after the pattern and define how the search is performed.
Syntax:
Example:
Explanation:
-
gsearches globally (finds all matches) -
imakes the match case-insensitive
List of RegExp Flags in JavaScript
| Flag | Name | Purpose |
|---|---|---|
g | Global | Finds all matches |
i | Case-insensitive | Ignores letter case |
m | Multiline | Changes ^ and $ behavior |
s | DotAll | Allows . to match newlines |
u | Unicode | Enables full Unicode support |
y | Sticky | Matches from last index only |
Global Flag (g)
Finds all occurrences instead of stopping at the first match.
Explanation:
Returns all occurrences of apple as an array.
Case-Insensitive Flag (i)
Ignores case while matching text.
Explanation:
Matches Hello, hELLo, and HELLO.
Multiline Flag (m)
Changes how ^ and $ work in multi-line strings.
Explanation:
^second matches second at the start of the second line.
DotAll Flag (s)
Allows the dot (.) to match newline characters.
Explanation:
With s flag, . matches the newline character between Hello and World.
Unicode Flag (u)
Enables correct handling of Unicode characters and symbols.
Explanation:
Ensures proper matching of Unicode characters.
Sticky Flag (y)
Matches only from the current lastIndex position of the regex.
Explanation:
Matches only if a appears exactly at index 2.
Combining Multiple Flags
Multiple flags can be used together.
Explanation:
Finds all matches of one ignoring case.
Difference Between g and y Flags
Explanation:
-
gcontinues searching for the next match -
yonly matches at the exactlastIndexposition
Common Mistakes with RegExp Flags
-
Forgetting to use
gwhen multiple matches are required -
Using
^and$withoutmin multi-line strings -
Expecting
.to match new lines withouts -
Misunderstanding the behavior of the
yflag
Summary of RegExp Flags
| Flag | Behavior Change |
|---|---|
g | Finds all matches |
i | Ignores case |
m | Multiline anchors |
s | Dot matches newline |
u | Unicode support |
y | Sticky position-based matching |
Conclusion
RegExp flags in JavaScript modify how patterns match text and make regular expressions more flexible and powerful. By using flags like g, i, m, s, u, and y, text searching, validation, and parsing tasks become easier and more precise.