Skip to content Skip to sidebar Skip to footer

How To Convert A Regular Expression To A String Literal And Back Again?

How can I: Convert a JavaScript RegExp with flags to a String literal (think JSON), And convert that literal back to a regex? For example with the String 'the weather is nice tod

Solution 1:

You can use eval to get back the regular expression:

var myRe = RegExp("weather", "gi");
var myReString = myRe.toString();
eval(myReString); // => /weather/gi

NOTE: eval can execute arbitrary javascript expression. Use eval only if you're sure the string is generated from regular expression toString method.

Solution 2:

I'm not sure if this code works in all cases, but I'm sure that this can be done using regex:

var regex = newRegExp('^/(.+)/(.*)$')
functionstringToRegex(s) {
    var match = s.match(regex)
    returnnewRegExp(match[1], match[2])
}

var test = newRegExp("weather", "gi")

console.log(stringToRegex(test.toString()))
console.log(stringToRegex(test.toString()).toString() === test.toString())

Regular expression visualization

Debuggex Demo

Post a Comment for "How To Convert A Regular Expression To A String Literal And Back Again?"