-1

My use case is I get Regex from a api response, which I have to use for validation purpose.

I get such a response

{  
   valid:'/^4/',
   displayName:'Card'
}

Now i convert the regex string to valid Regex

var rec = new RegExp(res.valid); //  /\/^4\//

Which is not desired. How can i convert regex in stringified form to Valid regex (/^4/).

Atishay Baid
  • 339
  • 2
  • 7

1 Answers1

2

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
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875