Sometimes you want to construct a Regular Expression object dynamically from a string instead of a literal regex. It’s important to safely escape special characters in the string that is not intended to be regex syntax. Turned out, the swift army knife Lodash library has a dedicated escapeRegExp method for this sole purpose.
const _ = require('lodash') let escapedString = _.escapeRegExp('[lodash](https://lodash.com/)') console.log(escapedString) // => '\[lodash\]\(https://lodash\.com/\)'
Construct Regular Expression object from string:
let re = new RegExp(escapedString) let match = re.exec('Should only match [lodash](https://lodash.com/)') console.log(match) // [ // '[lodash](https://lodash.com/)', // index: 18, // input: 'Should only match [lodash](https://lodash.com/)', // groups: undefined // ] // => match[0] is the matched string
Bonus: should you only need the escape feature and don’t wish to include Lodash library to your code, the simple function below is sufficient:
function escapeRegExp(string) { return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string } // usage: let escapedString = escapeRegExp("All of these should be escaped: \ ^ $ * + ? . ( ) | { } [ ]"); console.log(escapedString) // => "All of these should be escaped: \\ \^ \$ \* \+ \? \. \( \) \| \{ \} \[ \] "
Creator and author at DEPHONY. I develop open-source/free software and write technical tutorials that are straight to the point to save readers’ time to learn and apply. Support my work by becoming a Patron 🙂