Escape JavaScript Regex characters using Lodash
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:
(more…)