Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Page 2 of 2 FirstFirst 12
Results 16 to 19 of 19

Thread: regex variable

  1. #16
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,023
    Thanks
    75
    Thanked 4,323 Times in 4,289 Posts
    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:
    Code:
        replace(eval("/"+var1+"/gi"), anything)
    and
    Code:
        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.)
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  2. #17
    New Coder
    Join Date
    Jun 2009
    Posts
    81
    Thanks
    0
    Thanked 8 Times in 8 Posts
    Old Pendant,

    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.

  3. #18
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,023
    Thanks
    75
    Thanked 4,323 Times in 4,289 Posts
    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.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  4. #19
    Regular Coder
    Join Date
    May 2012
    Location
    France
    Posts
    224
    Thanks
    0
    Thanked 32 Times in 30 Posts
    I forgott the / which is also to escape with javascript !

    Code:
    String.prototype.toRegExp=function(){return this.replace(/\\/g,'\\\\').replace(/(\[|\^|\$|\.|\||\?|\*|\+|\(|\)|\/)/g,'\\$1')}
    
    //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'


 
Page 2 of 2 FirstFirst 12

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •