JavaScript: Escape a string to use in a regular expression
JavaScript fundamental (ES6 Syntax): Exercise-239 with Solution
Escape String for Regex
Write a JavaScript program to escape a string to use in a regular expression.
- Use String.prototype.replace() to escape special characters.
Sample Solution:
JavaScript Code:
//#Source https://bit.ly/2neWfJ2
// Define a function 'escapeRegExp' to escape special characters in a regular expression pattern
const escapeRegExp = str =>
// Replace special characters in the input string 'str' with their escaped versions
str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
// Test the 'escapeRegExp' function with a string containing special characters
console.log(escapeRegExp('(test)')); // Output: \(test\)
Output:
\(test\)
Flowchart:

Live Demo:
See the Pen javascript-basic-exercise-239-1 by w3resource (@w3resource) on CodePen.
For more Practice: Solve these Related Problems:
- Write a JavaScript program that escapes all special characters in a string so it can be safely used in a regular expression.
- Write a JavaScript function that converts a string to a regex-safe string by prefixing special characters with a backslash.
- Write a JavaScript program that iterates over a string and escapes characters like . * + ? ^ $ { } ( ) | [ ] \.
- Write a JavaScript function that takes user input and returns an escaped version for constructing dynamic regex patterns.
Go to:
PREV : Factorial of Number.
NEXT : Check Parent Contains Child.
Improve this sample solution and post your code through Disqus
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.