Skip to content

Instantly share code, notes, and snippets.

@nknapp
Created March 17, 2017 21:54
Show Gist options
  • Save nknapp/16c37f13d8e0b02691061395ee4f7565 to your computer and use it in GitHub Desktop.
Save nknapp/16c37f13d8e0b02691061395ee4f7565 to your computer and use it in GitHub Desktop.
var _ = require('lodash')
function regex (strings, ...args) {
return new RegExp(String.raw(strings, ...args.map(_.escapeRegExp)))
}
var needle = '1*'
console.log('21111112'.match(regex`2${needle}2`)) // falsy
console.log('2221*1*222'.match(regex`2(${needle})+2`)) // truthy
@nknapp
Copy link
Author

nknapp commented Mar 17, 2017

You can use template-literals to dynamically create regular expressions and escape the dynamic parts.
This is much more readable then new RegExp('2('+_.escapeRegExp(needle)+')+2')

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment