1

If I have this string

const string = "/a|b|c/gi" // some regex here

How do I convert the string to regex?

The below approach doesn't work because the flags are in the string too.

const regex = new Regex(string);
GoodBoyNeon
  • 103
  • 7
  • See this where to put the flags using the RegExp constructor https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp – The fourth bird Aug 08 '23 at 07:11

1 Answers1

0

We can use the slice method to extract the pattern and flags from the string. The pattern is obtained by taking the substring between the first / and the last /. The flags are obtained by taking the substring after the last /.

Then RegExp constructor can be used to create a regular expression object using the extracted pattern and flags.

const string = "/a|b|c/gi"; 

const pattern = string.slice(1, string.lastIndexOf('/'));
const flags = string.slice(string.lastIndexOf('/') + 1);

const regex = new RegExp(pattern, flags);

console.log(regex);

The console.log(regex) statement will display the resulting regular expression object.