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?
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?
Share Improve this question asked Aug 1, 2012 at 0:16 John SmithJohn Smith 7215 gold badges14 silver badges30 bronze badges 2- 1 stackoverflow./questions/9089532/why-does-eval-exist – mVChr Commented Aug 1, 2012 at 0:21
- This might be relevant: stackoverflow./questions/8071292/… – hugomg Commented Aug 1, 2012 at 0:32
3 Answers
Reset to default 3Don't use eval, use the RegExp
object:
var myvar = '+ 2 -';
alert(myvar.replace(/\+|\-/ig, '-'));
Result: - 2 -
i
means it will ignore case.
Don't put your RegExp
inside quotes. Then you won't need to eval
it.
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:
- i: ignore-case
- g: global (multiple matches)
- 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).