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);
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);
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.