user2305193 user2305193 - 5 months ago 11
Javascript Question

How to convert a regular expression to a String literal and back again?

How can I:


  1. Convert a JavaScript RegExp with flags to a String literal (think JSON),

  2. And convert that literal back to a regex?



For example with the String
"the weather is nice today"
:

var myRe = new RegExp("weather","gi");
var myReToString = myRe.toString(); // myReToString is now "/weather/gi"

var myReCopy = /* How to get this copy only from myReToString ? */





To modify the original RegExp properties see torazaburo's answer.

Answer

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.