function stringToRegex(s, m) {
return (m = s.match(/^([/~@;%#'])(.*?)1([gimsuy]*)$/)) ? new RegExp(m[2], m[3].split('').filter((i, p, s) => s.indexOf(i) === p).join('')) : new RegExp(s);
}
console.log(stringToRegex('/(foo)?/bar/i'));
console.log(stringToRegex('#(foo)?/bar##gi')); //Custom delimiters
console.log(stringToRegex('#(foo)?/bar##gig')); //Duplicate flags are filtered out
console.log(stringToRegex('/(foo)?/bar')); // Treated as string
console.log(stringToRegex('gig')); // Treated as string
Run code snippetHide results