Reputation: 130750
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?
Upvotes: 2
Views: 400
Reputation: 349252
Use the RegExp constructor to create a pattern.
// The next line would escape special characters. Since you want to support
// manually created RegExps, the next line is commented:
// regex = regexp.replace(/([[^$.|?*+(){}])/g, '\\$1')
regex = new RegExp(regex);
// ^ Optionally, add the flags as a second argument, eg:
//regex=new RegExp(regex, 'i'); //Case-insensitive
UPDATE
You seem to misunderstand the usage of the RegExp
constructor. The "slash-notation" is the "primitive" way to create a Regular expression. For comparsion, consider (new
is optional):
"123" === new String(123)
false === new Boolean(1)
// Because a RegExp is an object, the strict compare `===` method evaluates to
// false if the pattern is not the same object.
// Example: /\d/ == /\d/ evaluates to false
// To compare a regex pattern, use the `pattern` property
/[a-z]/i.pattern === (new RegExp("[a-z]", "i")).pattern
The RegExp
constructor 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 (new
is optional):
Using constructor using slash-notation # Notice:
RegExp('[0-9]'); /[0-9]/ # no slashes at RegExp
RegExp('/path/to/file\.html$') /path\/to\/file\.html$/ # the escaped \
RegExp('i\'m', 'i') /i'm/i # \' vs ', 'i' vs /i
var regex = $('input').val(); //Example: '/^[0-9]+$/i'
// Using a RegEx to implement a Reg Exp, ironically..
regex = regex.match(/^\/([\S\s]+)\/([gim]{0,3})$/);
regex = regex || [, regex, ""]; // If the previous match is null,
// treat the string as a slash-less RegEx
regex = new RegExp(regex[1], regex[2]);
regex.test('some string');
Upvotes: 2