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.

JavascriptSecurity Boundaries

Code

javascriptsnippet
12 lines
// 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: 0

Reading 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

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`.