Flags in JavaScript Regular Expressions (Live Playground)
Flags and modifiers are used in JavaScript regular expressions to control their behavior, making them more powerful and versatile. In this tutorial, we'll explore the different flags and modifiers available in JavaScript and how to use them effectively in your regular expressions.
Global Flag (g)
The global flag g
allows the regular expression to find all matches in the input string, not just the first one:
const pattern = /a/g; // matches all occurrences of 'a'
const string = 'JavaScript is amazing!';
const matches = string.match(pattern);
console.log(matches); // ['a', 'a', 'a', 'a']
Case-insensitive Flag (i)
The case-insensitive flag i
makes the regular expression match both uppercase and lowercase characters:
const pattern = /javascript/i; // matches 'javascript' regardless of case
const string1 = 'JavaScript is amazing!';
const string2 = 'JAVASCRIPT is amazing!';
console.log(pattern.test(string1)); // true
console.log(pattern.test(string2)); // true
Multiline Flag (m)
The multiline flag m
allows the regular expression to match patterns at the beginning and end of lines within a multiline string:
const pattern = /^JavaScript/m; // matches 'JavaScript' at the beginning of a line
const string = `JavaScript is amazing!
JavaScript is fun!`;
console.log(pattern.test(string)); // true
Dotall Flag (s)
The dotall flag s
makes the dot .
match any character, including line breaks:
const pattern = /Java.*Script/s; // matches 'Java' followed by any characters, then 'Script'
const string = `Java
Script`;
console.log(pattern.test(string)); // true
Unicode Flag (u)
The Unicode flag u
enables the correct processing of Unicode characters in the regular expression:
const pattern = /\p{L}/u; // matches any Unicode letter
const string = 'ö';
console.log(pattern.test(string)); // true
Sticky Flag (y)
The sticky flag y
makes the regular expression match from the exact position specified by the lastIndex property:
const pattern = /Java/y;
pattern.lastIndex = 3; // set the starting position
const string = 'JavaScript';
const match = pattern.exec(string);
console.log(match); // null (no match found)
Conclusion
Flags and modifiers in JavaScript regular expressions allow you to control their behavior for more powerful and versatile pattern matching. We covered global, case-insensitive, multiline, dotall, Unicode, and sticky flags. By combining these flags effectively, you can create complex and flexible regular expressions for a wide range of pattern-matching tasks.