2

I need to replace two different characters in a string all instances so i found this answer

<script type="text/javascript">
   var filter_out = eval("/1|3/ig");
   var myvar = "1 2 3";
   alert(myvar.replace(filter_out, "-"));
</script>

// - 2 -

It works, however this one does not:

<script type="text/javascript">
   var filter_out = eval("/\+|\-/ig");
   var myvar="+ 2 -";
   alert(myvar.replace(filter_out, "-"));
</script>

//SyntaxError: invalid quantifier: /+|-/ig

Never mind i fond that it works if i use

var filter_out = eval("/\\+|\\-/ig");

can someone explain why it has to be double \? Also i know "g" stands for global - all occurances, what "i" stands for?

John Smith
  • 681
  • 5
  • 13
  • 30
  • 1
    http://stackoverflow.com/questions/9089532/why-does-eval-exist – mVChr Aug 01 '12 at 00:21
  • This might be relevant: http://stackoverflow.com/questions/8071292/how-do-i-do-global-string-replace-without-needing-to-escape-everything – hugomg Aug 01 '12 at 00:32

3 Answers3

3

Don't use eval, use the RegExp object:

var myvar = '+ 2 -';
alert(myvar.replace(/\+|\-/ig, '-'));

Result: - 2 -

i means it will ignore case.

Michael Robinson
  • 29,278
  • 12
  • 104
  • 130
  • TypeError: can't supply flags when constructing one RegExp from another var filter_out = new RegExp(/\+|\-/, 'ig'); – John Smith Aug 01 '12 at 00:22
  • it just looks cleaner when i use eval and i can use same filter_out variable in multiple str_replace is there problem with using eval()? edit never mind found: stackoverflow.com/questions/9089532/why-does-eval-exist – John Smith Aug 01 '12 at 00:26
  • you can simply use `filter_out = /1|3/ig` instead of `filter_out = eval("/1|3/ig")`. That is what eval does anyway. If you want to have a regex which is initialized with a variable you can use `filter_out = new RegExp(pattern,modifiers)` - in this case pattern is `1|3` and modifiers is `ig`. – Vatev Aug 01 '12 at 00:37
0

Don't put your RegExp inside quotes. Then you won't need to eval it.

ErikE
  • 48,881
  • 23
  • 151
  • 196
0

As earlier stated, try to avoid using strings in regular expressions. Though it looks cleaner (I personally like looking at RegExp since its clearer), you'll run into less problems when using the shorthand notation /exp/switches.

There are three (one very seldom seen) switches you can use with a RegExp:

  1. i: ignore-case
  2. g: global (multiple matches)
  3. m: multi-line (sometimes necessary for strings with line breaks)

NOTE: Do NOT use eval() at all for this. In fact, you should probably not be using eval anywhere in your code -- I don't think I've used it in JS in ten years. There's almost always no need for it (there's libraries which use it sparingly when necessary).

Joe Johnson
  • 1,814
  • 16
  • 20