Qu'est-ce que Assistant RegExp.escape() ?
RegExp.escape(string) is a static method that returns a new string where every special regular expression character is escaped with a backslash. This makes the string safe to use inside a RegExp constructor when building dynamic patterns from user input. The method is part of Baseline 2025 (Chrome 132+) and replaces error-prone manual escape functions that developers have been writing and copying for decades.
Réponse rapide
Generate code using RegExp.escape(string) to safely escape special regex characters in user input before building dynamic RegExp patterns. Supports all 14 regex metacharacters. Available in Chrome 132+, Edge, Firefox, Node.js 20+. No more manual escape regex chains.
Limites
- Not available in environments without Baseline 2025 support. Use a polyfill or the traditional manual replace function for older Node.js versions and legacy browsers.
- RegExp.escape() only handles string inputs. For RegExp flags or pattern options, you must still build the full pattern string and flags array yourself.
- The method escapes every special character unconditionally. If you need to build a pattern that mixes literal user input with intentional regex syntax (like wildcards), you must separately handle the intentional syntax.
Comment utiliser cet outil
- Identify where you need to build a RegExp pattern from user-provided or variable input, such as search boxes or filter inputs.
- Pass the input string to RegExp.escape() before inserting it into the pattern string for the RegExp constructor.
- Use the escaped string in your RegExp pattern: new RegExp(RegExp.escape(userInput), 'gi').
- Review the generated code included in the tool output, which shows both the native method and the manual escape function for comparison.
A quoi il sert
- Build a client-side search filter where user keystrokes are turned into a regex for live filtering — escaping prevents invalid or injected patterns from breaking the regex.
- Create a find-and-replace UI where the user types a literal string to search for and a replacement. Escaping ensures that characters like . or * are treated as literals.
- Highlight search terms in text content by constructing a RegExp from user input and wrapping matches in a span — escaping guarantees the pattern is syntactically valid.