RegExp.escape Quotes Dynamic Patterns
RegExp.escape quotes every metacharacter in dynamic patterns, so user input can only ever match literally instead of acting as syntax.
Code
// Build patterns from raw input: RegExp.escape quotes every special
// character so the escaped text can only ever match literally
const needle = 'price: $9.99 (each)?';
console.log('escaped:', RegExp.escape(needle));
const text = 'a price: $9.99 (each)? yes';
const re = new RegExp(RegExp.escape(needle), 'g');
console.log('escaped matches:', (text.match(re) ?? []).length);
// The same input unescaped is valid syntax but matches nothing
const unescaped = new RegExp(needle, 'g');
console.log('unescaped matches:', (text.match(unescaped) ?? []).length);Output
Captured from a sandboxed run of this snippet in the build pipeline.
escaped: \x70rice\x3a\x20\$9\.99\x20\(each\)\?
escaped matches: 1
unescaped matches: 0Reading the snippet
Demo state sits in top-level bindings: needle, text, re, unescaped.
Watch out for
- It is dependency-free in the strict sense — the import list, if any, is empty of packages.
Using it
The demo output is labeled (escaped:, escaped matches:, unescaped matches:); each label names the call that printed it.
Key statements
const re = new RegExp(RegExp.escape(needle), 'g');
const text = 'a price: $9.99 (each)? yes';
const unescaped = new RegExp(needle, 'g');
Interactive Tools for This Topic
Regex Escape GeneratorEscape plain text so it can be embedded safely in a JavaScript RegExp, covering all metacharacters like dots, brackets, braces, and backslashes.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.Regular Expression TesterTest regular expressions against sample text with live match highlighting, capture group extraction, and flags support for global, case-insensitive, and multiline modes.Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.
FAQ
- Does the code pull in any external packages?
- No external packages are involved; every call resolves to a built-in API. Its state lives in module-level bindings: `needle`, `text`, `re`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.