# RegExp.escape()

> The `RegExp.escape()` static JS method escapes special characters in a string so it can be used in a regular expression.

## How do I escape a string for use in a RegExp in JavaScript?

The static method that returns a string with all regular expression syntax characters escaped. Allows safely building a `RegExp` from user input without writing custom escaping functions.

- Topic: Specials
- Type: method
- Browser support: Chrome 136+, Chrome Android 136+, Edge 136+, Firefox 134+, Firefox Android 134+, Safari 18.2+, Safari iOS 18.2+

## Example

Wrong:

```js
const re = new RegExp(query, 'gi');
const html = text.replace(re, '<mark>$&</mark>');
```

Right:

```js
const re = new RegExp(RegExp.escape(query), 'gi');
const html = text.replace(re, '<mark>$&</mark>');
```

Unescaped input like 'a.b' or 'c++' changes the pattern or throws; `RegExp.escape()` makes it match literally.

## Common mistakes

- Building a regex from user input without escaping, so '.' or '(' changes the pattern.

## Key points

- User input is passed through `RegExp.escape()` before it goes into `new RegExp()`.
- There is no hand-written replace with a list of special characters.
- A plain substring check uses `includes()` instead of a regular expression.

## Interview questions

### Do I need a fallback for RegExp.escape()?

In older browsers, yes. Feature-detect it with `typeof RegExp.escape === 'function'` and fall back to a small replace-based escape helper.

### Can I use replaceAll() instead of escaping a regex?

Yes, for plain text, `str.replaceAll(query, value)` with a string pattern needs no escaping at all.

## Related cards

- [RegExp](https://wonderium.dev/js/regexp.md)
- [.replaceAll()](https://wonderium.dev/js/string-replace-all.md)
- [String.includes()](https://wonderium.dev/js/string-includes.md)
- [.match()](https://wonderium.dev/js/string-match.md)

---

- Level: [JavaScript](https://wonderium.dev/js.md)
- HTML version: https://wonderium.dev/js/regexp-escape
- Last updated: 2026-11-25
