In JavaScript Regular Expressions, flags (also known as modifiers) are used to change the default searching behavior. By default, a regex search stops after the very first match it finds, and it is strictly case-sensitive.
Flags allow you to perform global searches, case-insensitive searches, and more. You add flags directly after the closing slash of a regular expression (e.g., /pattern/g).
Here is a table of the most commonly used flags in JavaScript:
| Flag | Name | Description |
|---|---|---|
i |
Ignore Case | Makes the search case-insensitive. (A matches a) |
g |
Global | Performs a global match. Finds all matches rather than stopping after the first match. |
m |
Multiline | Makes the start (^) and end ($) boundary assertions match the beginning and end of each line rather than the whole string. |
s |
DotAll | Allows the dot . metacharacter to match newline characters (\n). |
u |
Unicode | Enables full Unicode matching (useful for emojis and extended characters). |
y |
Sticky | Forces the search to only look at the exact lastIndex position in the string. |
i Flag (Case-Insensitive)By default, regular expressions are case-sensitive. The i flag tells the RegExp engine to ignore the casing.
let text = "Visit LONDON!";// Without 'i' flag: returns -1 (Not found because of capital L) console.log(text.search(/london/));
// With 'i' flag: returns 6 (Match found!) console.log(text.search(/london/i));
g Flag (Global Match)By default, methods like replace() or match() will only process the first occurrence of a pattern. If you want to find or replace all occurrences in a string, you must use the g flag.
let str = "The rain in SPAIN stays mainly in the plain";// Replace without 'g' (Only replaces the first "in") console.log(str.replace(/in/, "XX"));
// Replace with 'g' (Replaces ALL occurrences of "in") console.log(str.replace(/in/g, "XX"));
You can combine multiple flags together to compound their effects! Just place them next to each other after the closing slash. Order does not matter (/gi is the same as /ig).
let str = "The rain in SPAIN stays mainly in the plain";// We want to replace ALL "in", ignoring case! let result = str.replace(/in/gi, "XX");
console.log(result);
Which flag tells the RegExp engine to find all matches in a string instead of stopping at the first one?