I want a way to generate a regex from a string that will match only the original string.
i.e.
myRegexGenerator('babies/canfly?a=probably-not');
// returns an equivalent to /^babies\/canfly\?a=probably-not$/
I want a way to generate a regex from a string that will match only the original string.
i.e.
myRegexGenerator('babies/canfly?a=probably-not');
// returns an equivalent to /^babies\/canfly\?a=probably-not$/
You basically just need to escape any special regex characters. Then create a RegExp object.
var input = 'babies/canfly?a=probably-not';
new RegExp(input.replace(/[^$]/g, "\$&"));
Obviously the more special codes you catch and escape before making the RegExp the more robust it will be to different inputs. You can use a reference like regular-expressions.info to make sure you cover everything. Or you can just cover whatever characters you know are possible.