When defining a regex in a string, we don't use /
around it. Those are the literal form. By passing a string with /
on it into new RegExp
, you're making it think the /
are part of the expression.
Just remove them:
var rec = new RegExp(res.valid.substring(1, res.valid.length - 1));
Actually, thinking about it, you may need to go further than that, if there are flags on the regex (like valid: '/^x/i'
):
var rec;
var valid = res.valid;
var match;
if (valid[0] === "/") {
match = valid.match(/\/([gimuy]*)$/);
}
if (match) {
rec = new RegExp(valid.substring(1, valid.length - match[0].length), match[1] || "");
} else {
rec = new RegExp(valid);
}
var res = {
valid: "/^x/i"
};
var rec;
var valid = res.valid;
var match;
if (valid[0] === "/") {
match = valid.match(/\/([gimuy]*)$/);
}
if (match) {
rec = new RegExp(valid.substring(1, valid.length - match[0].length), match[1] || "");
} else {
rec = new RegExp(valid);
}
console.log(rec.test("xyz")); // true
console.log(rec.test("Xyz")); // true
console.log(rec.test("zyx")); // false