The RegExp.escape() Method
Example
Create a regular expression that matches the string "[*]":
// Escape a text for to use as a regular expression
const safe = RegExp.escape("[*]";
// Build a new reglar expression
const regex = new RegExp(safe);
// Text to replace within
const oldText = "[*] is a web school.";
// Perform the replace
const newText = oldText.match(regex, "W3Schools");
Try it Yourself »
Description
The RegExp.escape()
method returns string where characters that belongs
to the regular expression syntax are escaped.
This makes it possible to treat characters like +, *, ?, ^, $, (, ), [, ], {, }, |, and \ literally, and not as part of a regular expression.
Syntax
RegExp.escape(string)
Parameter Values
Parameter | Description |
---|---|
string | Required. The string to be searched |
Return Value
Type | Description |
---|---|
String | An string containing with regular expression characters are escaped |
Browser Support
RegExp.escape()
is supported all in modern browsers since May 2025:
Chrome 136 | Edge 136 | Firefox 134 | Safari 18.2 | Opera 121 |
Apr 2025 | May 2025 | Jan 2025 | Des 2024 | Jun 2025 |
Regular Expression Search Methods
In JavaScript, a regular expression text search, can be done with different methods.
With a pattern as a regular expression, these are the most common methods:
Example | Description |
---|---|
text.match(pattern) | The String method match() |
text.search(pattern) | The String method search() |
pattern.exec(text) | The RexExp method exec() |
pattern.test(text) | The RegExp method test() |