I just created a function for that. Check it.
- Substring from 1 ( to avoid first
/) to last index of /). -> we got the pattenr.
- substring from last index of
/ +1 to string length -> got the flags
Then pass the 2 arguments to the new RegExp function
function formRegEx(str){
var reg=str.substring(1,str.lastIndexOf('/'));
var flags=str.substring(str.lastIndexOf('/')+1,str.length);
return new RegExp(reg,flags);
}
console.log(formRegEx('/abc/i'));
console.log(formRegEx('/[a-zA-Z]/ig'));
Update
From OP's comment on question, abc/i may present which should be treated as invalid.
So, a test can be done to check the validity
/^\/.*\/[igm]*$/
and then check for no existence of // by testing against
/[^\\]\/[^igm]/
The above function can be rewritten as
function formRegEx(str){
if(!/^\/.*\/[igm]*$/.test(str)) return "Invalid RE";
if(/[^\\]\/[^igm]/.test(str)) return "Invalid RE";
var reg=str.substring(1,str.lastIndexOf('/'));
var flags=str.substring(str.lastIndexOf('/')+1,str.length);
return new RegExp(reg,flags);
}
console.log(formRegEx('/abc/ig')); // true
console.log(formRegEx('/abc//i')); // false
console.log(formRegEx('/a/bc/i')); //false
console.log(formRegEx('/[a-zA-Z]/ig')); // true
console.log(formRegEx('abc/ig')); // invalid
console.log(formRegEx('abci')); // invalid
console.log(formRegEx('/abc/ik')); // invalid
new RegExp(pattern)? -> developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…/\/abc\/i/