Skip to content

This notebook belongs to

Sadat Jubayer

Senior Software Engineer at Premio

If found, please return to hello@jubayer.dev

Vol. 7Seven years of building

Started
January 2020
Everyday tools
TypeScript, Vue, React, Next.js, NestJS, React Native
Education
B.Sc. CSSE, AIUB, 2020
1 min readJavaScript

Match literal text with RegExp.escape

Use RegExp.escape when inserting literal search text into a larger regular expression that checks a filename suffix.

A filename filter passes the text from a search box into new RegExp(). Searching for (draft) matches names without parentheses, because the regex reads the parentheses as a group. Searching for a lone ( throws before the filter can return any results.

Escape the input before you build the pattern

Use RegExp.escape() around the text that should match as written. Keep the surrounding pattern and flags under your control. Use a browser or Node version that supports the method. In this example, the filename must end with the search text followed by .txt.

const names = ['draft.txt', '(draft).txt', '(draft).txt.bak', '(.txt']
const ending = (text) => new RegExp(RegExp.escape(text) + '\\.txt$', 'i')

for (const query of ['(draft)', '(']) {
  const pattern = ending(query)
  console.log(names.filter((name) => pattern.test(name)))
}

The first filter returns ['(draft).txt']. The second returns ['(.txt'] without throwing.

The escape call makes each search character literal. The \\.txt$ fragment in the string adds the required extension and anchors the match at the end. Since the pattern has no start anchor, a longer filename ending in (draft).txt would also match. Add a start anchor if the entire name should match.

Build the regex once per search when filtering a list. Decide how to handle an empty query before building it. An empty escaped string contributes no characters, so the extension pattern would match any of the eligible filenames.

Let the standard function choose the escapes

The output can look longer than expected. A leading ASCII digit or letter uses a hexadecimal escape so the fragment can sit after an escape in a larger pattern without merging into it. A hyphen can also appear as a hex escape. Use the return value as a pattern fragment and leave its spelling alone.

If the search is a literal substring test with no pattern around it, use includes(). If the filename search only needs ASCII case folding, lowercasing both strings and using endsWith() also works for this suffix check.