JavaScript: Search for literal text inside a dynamic regular expression
A label such as report[1].csv contains regular-expression syntax. Inserting it directly into a pattern changes what the search accepts. Escape the variable part when the rest of the pattern needs regex behavior.
Set up
Tested on Debian 13 Linux with Node.js v24.19.0. Use Bash, Node.js on your PATH, a text editor, and the mktemp, rm and rmdir utilities. No packages or network access are needed. Keep the same terminal through cleanup. Stop if setup fails before saving the source.
start_dir="$PWD"
work_dir="$(mktemp -d)" || exit 1
cd -- "$work_dir" || exit 1Run the example
Save as javascript-escape-literal-regexp.mjs:
import assert from 'node:assert/strict';
const label = 'report[1].csv';
const unsafe = new RegExp(`^${label}$`, 'u');
const literal = new RegExp(`^${RegExp.escape(label)}$`, 'u');
console.log('Raw pattern accepts report1Xcsv:', unsafe.test('report1Xcsv'));
console.log('Escaped pattern accepts label:', literal.test(label));
console.log('Escaped pattern accepts lookalike:', literal.test('report1Xcsv'));
assert.equal(unsafe.test('report1Xcsv'), true);
assert.equal(literal.test(label), true);
assert.equal(literal.test('report1Xcsv'), false);
for (const value of ['a+b', '(draft)', 'x-y', 'a/b', '\\', '']) {
const exact = new RegExp(`^${RegExp.escape(value)}$`, 'u');
assert.equal(exact.test(value), true);
assert.equal(exact.test(`${value}x`), false);
}
console.log('Punctuation and empty-text checks: passed');Run:
node javascript-escape-literal-regexp.mjsObserved output:
Raw pattern accepts report1Xcsv: true
Escaped pattern accepts label: true
Escaped pattern accepts lookalike: false
Punctuation and empty-text checks: passedKeep the pattern structure fixed
The brackets in the raw pattern form a character class, and its dot matches any permitted character. Escaping the label makes those characters literal. Only the fixed anchors remain regex syntax.
For exact equality, use candidate === label; for a literal substring search, use candidate.includes(label). Escaping is useful when a literal term belongs inside a larger pattern, such as a fixed prefix followed by one of several literal labels. The example keeps matching case-sensitive and leaves off the stateful global and sticky flags.
Check runtime support and boundaries
The ECMAScript RegExp.escape specification also handles characters that need hexadecimal escapes in some pattern contexts. Hand-written replacement lists can miss those cases. Use a runtime that provides the method; this example was executed with the version listed above.
Escaping controls pattern interpretation. It does not validate a filename, authorize a resource, or bound matching time for the rest of an application-supplied pattern. The example accepts an empty label deliberately. Add a length rule if your application forbids that input, and bound input sizes when handling untrusted text.
Clean up
Remove the saved file and empty scratch directory. If the directory is not empty, inspect its contents before removing anything else.
rm -- javascript-escape-literal-regexp.mjs
cd -- "$start_dir" || exit 1
rmdir -- "$work_dir"
unset start_dir work_dirAcknowledgements
This post was created with assistance from AI.