user2305193 user2305193 - 1 year ago 54
Javascript Question

Is there a more elegant solution to convert regular expression to string and back again?

Is there a more elegant solution to

  1. convert a javascript regular expression to string

  2. and back again?

Here's my approach:

//teststring is "the weather is nice today"
var myRe = new RegExp("weather","gi")
myRe = myRe.toString();
//myRe is now "/weather/gi"
myRe = new RegExp(myRe.replace(/\//gi,"").slice(0,-2),"gi")
//myRe is /weather/gi again

edit: to modify the original RegExp properties see torazaburo's answer

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download