-4

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$/
theonlygusti
  • 11,032
  • 11
  • 64
  • 119
  • 1
    This sounds very strange. What are you intending to do? – str Aug 22 '16 at 08:21
  • 3
    Just [escape](http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript) it and add `^` and `$`. – georg Aug 22 '16 at 08:22
  • 2
    What is purpose of making this regex? – anubhava Aug 22 '16 at 08:23
  • 1
    Either do what georg said or just compare the strings directly without using a regex, if the latter is doable in whatever code you've written (I'm sure you have your reasons). – Jason C Aug 22 '16 at 08:25
  • To search strings inside other strings you have methods like *indexOf()*, if you need to count the time the string matches you could easily do it with a loop and *indexOf()* as you can give a starting index as second parameter. – Mario Santini Aug 22 '16 at 08:28
  • The purpose is to make a function which can accept either a string or a regex as an argument, but internally uses a regex equivalent of that argument, for url path matching. – theonlygusti Aug 22 '16 at 10:23

1 Answers1

1

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.

Whothehellisthat
  • 2,072
  • 1
  • 14
  • 14