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:


Find duplications in array using Lodash (JavaScript)

Lodash is my favorite JavaScript library that includes many useful data manipulation utilities in functional programming style. It can run in Node.js and browsers.

The below snippet is an example of using 2 functions filter and includes to find duplications in an array.

const _ = require('lodash')

const values = [1,2,2,3,4,1]
const duplications = _.filter(values, (value, i) => {
 return _.includes(values, value, i + 1)

// => [1, 2]