How to Escape RegExp Special Characters in Javascript (or Typescript)
![Jasser Mark Arioste Jasser Mark Arioste](https://api.reacthustle.com/image?url=https://static.reacthustle.com/uploads/f4f5cbec4f331597effb22a00.jpeg?w=40&q=100)
Jasser Mark Arioste
This tutorial shows you three ways to escape special characters in query strings.
Why Do you need to escape regex special characters? #
There was an issue in my projects where the user could not find records if the plus(+) symbol was included in the query string. When searching for users/records with the plus symbol included in the email field, the database did not return any results. I used MongoDB as the database and used the $regex operator.
The problem was that the query string was not escaped and MongoDB was interpreting the plus symbol differently. This is because the plus (+) symbol is a special regex character that has to be escaped!
❌ Incorrect query: {email: {$regex: /user+test/, options: "i"}}
✅ Correct query(the plus sign is now escaped!): {email: {$regex: /user\+test/, options: "i"}}
What characters need to be escaped? #
You need to escape all special regex characters so that they will be treated as regular strings. The following is the list of special characters in regex in javascript:
!#$%^&*)(+=.<>{}[]:;'"|~`_-
1
More info here:
Using Plain Javascript/Typescript #
To transform a string to its escaped version, we'll create a regex of all the special characters and use javascript string.replace
function. I prefer this method since we don't have to install a package.
const REGEXP_SPECIAL_CHAR = /[\!\#\$\%\^\&\*\)\(\+\=\.\<\>\{\}\[\]\:\;\'\"\|\~\`\_\-]/g; //base query const queryString = 'user+test@gmail.com'; // prepend a backslash and insert the matched character. const escapedQuery = query.replace(REGEXP_SPECIAL_CHAR, '\\$&'); console.log(escapedQuery); // user\+test@gmail\.com //for example if we want to use it in MongoDB: // db.users.find({ // email: {$regex: new RegExp(escapedQuery, "i")} // })
123456789101112131415
Using Lodash #
If you're using lodash
in your project, you'll be able to save time by using lodash's escapeRegex
function. Lodash is a modern javascript utility library that is still great to use in many projects!
import escapeRegExp from "lodash/escapeRegExp" const queryString = 'user+test@gmail.com'; const escapedQueryLodash = escapeRegExp(queryString); console.log(escapedQueryLodash); // user\+test@gmail\.com
123456
Using escape-string-regexp
package
#
If you're not using lodash due to its size or don't want to bother with the first method. You can use the escape-string-regexp npm package, it has a very small size and is very good at what it does. It has a very small footprint (256b) and is also written in typescript.
Installation
yarn add escape-string-regexp # or npm install escape-string-regexp
1234
Usage
import escapeRegExp from 'escape-string-regexp'; const queryString = 'user+test@gmail.com'; const escaped = escapeRegExp(queryString) console.log(escaped) //user\+test@gmail\.com
12345
Conclusion #
We were able to learn three different ways to escape special regexp characters in javascript.
If you like this tutorial please leave a like or share! If you want to be updated on our tutorials, please subscribe to our newsletter or follow me on Twitter!
Resources #
Regular Expressions Docs - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
String.prototype.replace
Docs - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace
Lodash Docs - https://lodash.com/docs/4.17.15
Credits: Image by David Mark from Pixabay