最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript str_replace use "plus" and "minus" characters in regex - Stack Overflow

programmeradmin1浏览0评论

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
Add a ment  | 

3 Answers 3

Reset to default 3

Don'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:

  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).

发布评论

评论列表(0)

  1. 暂无评论