RegExp.escape()
The RegExp.escape() static method escapes any potential regex syntax characters in a string, and returns a new string that can be safely used as a literal pattern for the RegExp() constructor.
When dynamically creating a RegExp with user-provided content, consider using this function to sanitize the input (unless the input is actually intended to contain regex syntax). In addition, don't try to re-implement its functionality by, for example, using String.prototype.replaceAll() to insert a \ before all syntax characters. RegExp.escape() is designed to use escape sequences that work in many more edge cases/contexts than hand-crafted code is likely to achieve.
Browser support
| Feature | Desktop | Mobile | ||||
|---|---|---|---|---|---|---|
| Chrome | Edge | Firefox | Safari | Chrome Android | Safari iOS | |
| 136 | 136 | 134 | 18.2 | 136 | 18.2 | |
Syntax
const userInput = 'price: $10.00 (USD)';
const escaped = RegExp.escape(userInput);
// 'price\\: \\$10\\.00 \\(USD\\)'
const regex = new RegExp(escaped);
regex.test('price: $10.00 (USD)'); // true Live demo
yu-za-input. safeall search
Inputsymbol positivecharacter and, searchresult hilight..
Use cases
-
Safe dynamic search
Escape user input before building a regex so characters like . or * are treated literally.
-
Pattern-building utilities
Combine trusted regex structure with escaped variable text for configurable search tools.
Cautions
- Escaping makes text literal; do not use it when you intentionally want users to supply raw regex syntax.
- It helps with pattern construction, but you still need broader performance and validation safeguards for complex searches.
Accessibility
- Safer pattern construction reduces validation bugs that can lead to confusing error states for users.