I have a box where the user inputs a regex, and in Javascript I take that value and have another string tested with it like so: (this is an abstraction of my real issue)
var regex = $('input').val();
regex.test('some string');
The only way I know to make sure to cast the regex to a safe Object type, is to use eval().
Is that the best way of casting it?
Use the RegExp constructor to create a pattern.
UPDATE
You seem to misunderstand the usage of the
RegExpconstructor. The “slash-notation” is the “primitive” way to create a Regular expression. For comparsion, consider (newis optional):The
RegExpconstructor takes two arguments, with the second one being optional:String (optional) Flags A combination of:
i(ignore case)g(global match)m(multi-line (rarely used)).Examples (
newis optional):Implementing a “RegExp” form field using slash-notation