Created
March 17, 2017 21:54
-
-
Save nknapp/16c37f13d8e0b02691061395ee4f7565 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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')