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…)

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)
})

console.log(duplications) 
// => [1, 2]

Explain:

(more…)