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](')

// => '\[lodash\]\(https://lodash\.com/\)'

Construct Regular Expression object from string:

let re = new RegExp(escapedString)

let match = re.exec('Should only match [lodash](')
// [
//   '[lodash](',
//   index: 18,
//   input: 'Should only match [lodash](',
//   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: