liveBook · Manning

Regular expression flag

As explained in Secrets of the JavaScript Ninja, Third Edition

A modifier that changes the matching behavior or returned information of a regular expression.

A regular-expression flag modifies how a pattern matches or what information its results contain. Flags let the same pattern behave differently without changing its terms. section 12.2.1

JavaScript flags tune different parts of matching:

  • d adds capture-group start and end indices to results; g matches all occurrences; i ignores case. section 12.2.1
  • m makes ^ and $ match line boundaries; s lets . match newlines. section 12.2.1
  • u and v enable Unicode features; v is generally preferred. y attempts a match at the last match position without gaps. section 12.2.1

Add flags to a pattern

Write flags after the closing slash, as in /test/ig, or pass them as the RegExp constructor’s second argument: new RegExp("test", "ig"). Here, i makes matching case-insensitive and g enables global matching. Global regexes continue matching through the string; local ones stop after a match. section 12.2.1 section 12.7

How Secrets of the JavaScript Ninja, Third Edition covers it

How deep it goes
Define eight flags by effect and show literal and constructor syntax, while deferring detailed regex terms and operators.
Examples
Illustrate flags with /test/ig and new RegExp("test", "ig"), plus case-insensitive and global matching behavior.
What you can do after
Configure regex literals or RegExp instances to control case sensitivity, global matching, line anchors, dotAll, Unicode, and sticky behavior.
How it connects
Connect flags to regex literals, the RegExp constructor, capture groups, Unicode, and String match and matchAll methods.

Also explained in

Compare how 2 books explain regular expression flag →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Secrets of the JavaScript Ninja, Third Edition. The section links point to the parts of the book it draws on.