Regular expressions and text guides

Escape literal text before building a regex

Distinguish literal search from regex search and account for JavaScript string and regex escaping layers.

Nav Tools ·

Metacharacters change meaning

A period matches an arbitrary character in a regex, while parentheses define groups. A filename copied directly into a pattern can therefore match unintended text.

For a literal search, escape the pattern metacharacters or use a literal string search API. Do not turn every user search into a regex unnecessarily.

Literal: file(1).json
Pattern: file\(1\)\.json

Separate source-string escaping

A pattern field accepts the regex pattern directly. A JavaScript string passed to RegExp adds a string-literal escaping layer first.

Keep those forms beside each other when debugging. JSON configuration containing a pattern adds JSON string escaping too.

Pattern field: \d+
JavaScript: new RegExp("\\d+")

Use a maintained escaping API

RegExp.escape exists in recent JavaScript environments to prepare literal text for regex construction. Check support or use a vetted compatibility implementation.

Ad hoc replacements can miss context-sensitive cases when embedding text in a larger pattern. A JSON string escaper is not a regex escaper.

Test hostile-looking literals

Include brackets, backslashes, dollar signs and a long string in a literal-search fixture. Each should match itself rather than act as regex syntax.

If the feature intentionally accepts regex, expose that mode explicitly and bound input and execution time. Escaping and limiting execution solve different problems.

References

← Regular expressions and text guides