JS RegExp Flags
In this page:
/pattern/g // global
/pattern/i // case-insensitive
/pattern/m // multiline
/pattern/gi // combined
The Global Flag (g)
Without g, a regex only finds the first match in a string and stops -- with g, methods like .match() and .replace() find and act on every match throughout the entire string, not just the first occurrence.
उदाहरण: The Global Flag (g)
console.log("cat cat cat".match(/cat/)); // only the first match
console.log("cat cat cat".match(/cat/g)); // every match
The Case-Insensitive Flag (i)
The i flag makes a pattern match regardless of upper or lower case -- /cat/i matches "cat", "CAT", "Cat", and any other capitalization -- useful whenever the exact case of the input cannot be relied upon, like validating a user-entered word.
उदाहरण: The Case-Insensitive Flag (i)
console.log(/cat/i.test("CAT")); // true, case-insensitive
The Multiline Flag (m)
By default, ^ matches only the very start of the entire string and $ only the very end, even in a multi-line string -- the m flag changes this so ^ and $ instead match the start and end of each individual line within the string.
उदाहरण: The Multiline Flag (m)
const text = "line one\nline two";
console.log(text.match(/^line/gm)); // matches start of each line
The Unicode Flag (u)
The u flag enables full Unicode-aware pattern matching, correctly handling characters outside the Basic Multilingual Plane (like many emoji), which without this flag can be misinterpreted as two separate characters instead of one.
उदाहरण: The Unicode Flag (u)
console.log(/\u{1F600}/u.test("\u{1F600}")); // correctly handles characters outside the basic plane
Combining Multiple Flags
Flags can be combined in any order after the closing slash -- /pattern/gi applies both global and case-insensitive matching at once, /pattern/gm combines global and multiline, and so on, letting you mix exactly the behaviors a given task needs.
उदाहरण: Combining Multiple Flags
console.log("Cat cat CAT".match(/cat/gi)); // combines global + case-insensitive
Chapter Quiz — Complete all 26 topics to unlock
0/26 topics done
Complete these topics first:
- JS JSON
- JS Regular Expressions
- JS Fetch API
- JS LocalStorage and SessionStorage
- JS Cookies
- JS setTimeout and setInterval
- JS Event Loop
- JS Web Workers
- JS Service Workers
- JS AJAX
- JS AJAX Intro
- JS AJAX XMLHttp
- JS AJAX Request
- JS AJAX Response
- JS AJAX XML
- JS AJAX PHP
- JS AJAX Database
- JS JSONP
- JS RegExp Flags
- JS RegExp Classes
- JS RegExp Metachars
- JS RegExp Assertions
- JS RegExp Groups
- JS RegExp Quantifiers
- JS JSON HTML
- JS JSON vs XML