Building a regex from a search box breaks as soon as someone types a dot, a bracket or a question mark. Everyone has a little escapeRegExp helper copied from somewhere. JavaScript now has one built in.
const query = "1.5 (beta)?";
const re = new RegExp(RegExp.escape(query), "gi");
"Release 1.5 (beta)? is out".replace(re, (m) => `<mark>${m}</mark>`);
RegExp.escape("a.b"); // \x61\.b
new RegExp(RegExp.escape("a.b")).test("axb"); // false
Every character with a special meaning in a pattern gets a backslash, so the regex matches the text literally. Without escaping, . matches any character and (beta)? becomes an optional group, which turns a simple search into the wrong one, or throws a SyntaxError for input like a single (.
The output looks odder than a hand made helper: a leading digit or letter and some punctuation are written as \x escapes, like \x31 for the “1” above. That is deliberate, so the result stays safe even when you put it right after other pattern text such as a \1 back reference.
My mark example puts raw input into HTML, so in real code escape it for HTML too, or build the result with DOM methods.
Support: Chrome 136, Firefox 134, Safari 18.2 and Node.js 24. For plain substring searches, includes() or replaceAll() with a string need no regex at all.
Further reading: MDN: RegExp.escape()