demo · v135

Dynamic Highlighter

A real-world use case from the TC39 proposal motivation: build a multi-term highlighter from a list of arbitrary, user-supplied tokens. Without RegExp.escape, any user-supplied ., (, or $ turns into a metacharacter and either over-matches or throws. With it, the combined alternation regex is bullet-proof.

RegExp.escape: ?

highlighted document

naive pattern (no escape)

safe pattern (RegExp.escape)

the code

// Build one alternation regex from a list of arbitrary terms.
const safe = terms
  .map((t) => RegExp.escape(t))   // each term becomes a literal pattern
  .join("|");
const re = new RegExp(`(${safe})`, "gi");
doc.replace(re, (m) => `<mark>${m}</mark>`);

see also