liveBook · Manning

Regex escaping

As explained in Secrets of the JavaScript Ninja, Third Edition

Regex escaping is the use of a backslash to make a special character match literally or to represent a control character.

A backslash makes a regex metacharacter match literally. For example, /\\/ matches a backslash; without escaping, special characters such as ^, $, ., and * have regex meaning. section 12.2.2

Regex literals and strings

In a JavaScript regex literal, write /\\/ to match a backslash. The equivalent constructor is new RegExp("\\\\"): string literals also use backslash escapes, so the backslashes must be doubled. section 12.2.2

ESLint’s no-invalid-regexp rule can help catch invalid special-character usage that would otherwise cause a runtime error. section 12.2.2

How Secrets of the JavaScript Ninja, Third Edition covers it

How deep it goes
Explains escaping metacharacters and backslashes, and contrasts regex literals with constructor strings.
Examples
Compares /\\/ with new RegExp("\\\\") as equivalent ways to match a backslash.
What you can do after
Apply escaping to match special characters in regex literals and constructor strings.
How it connects
Connects regex metacharacters with JavaScript string escaping and the RegExp constructor.

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.