It's not clear at all to me what your reason for using eval( ) is.
Is it simply so you can do it all in one line?
Not a good reason.
What's the difference between:
replace( (new RegExp( var1, "gi" ) ), anything )
Surely the second version is much more efficient, by avoiding the eval( ).
Even if eval( ) isn't evil, it's certainly less efficient than most anything else. (Especially in MSIE, unsurprisingly.)
I've evaluated your comment and of course you're right. Thank you. I do fall back to eval when I believe it's required, but in the examples posted here I used eval because its a legal (if unwelcome) option that provided a solution. There is no doubt that
replace((new RegExp(var1,"gi")),var2) is superior and more desirable, and as such, I stand corrected - in my evaluations.:o
I'd be really interested to see a situation where eval() is *REQUIRED*.
Other than parsing JSON that is returned by an AJAX call or something very similar.
I have yet to find a case where it is required, except when processing external JS data input.
//Example of use with all the «meta»characters
var something="[\\^$.|?*+()/"; // the slashe is to escape
alert(("foo"+something+"bar").replace(new RegExp(something.toRegExp(),'g'),''));// =>'foobar'