Skip to content

Instantly share code, notes, and snippets.

@belchior
Last active July 13, 2017 19:47
Show Gist options
  • Save belchior/7c32b03f48b75948a896a8bc2581f0fa to your computer and use it in GitHub Desktop.
Save belchior/7c32b03f48b75948a896a8bc2581f0fa to your computer and use it in GitHub Desktop.
Convert String with regex pattern to RegExp object
function toRegExp(text) {
var flags;
var reg;
text = typeof text === 'string' ? text : '';
flags = text.replace(/.*\/([igmy]*)$/, '$1');
reg = text.replace(/^\/(.*)\/[igmy]*$/, '$1');
return new RegExp(reg, flags);
}
@belchior
Copy link
Author

usage:

toRegExp('/^http:/gi')

/^http:/gi

toRegExp('/(a|b)+[c]*/g')

/(a|b)+[c]*/g

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment