0

Why in the first case, html em tags are printed normally whereas in the second test, they disappear.


var text = "text";
eval("var text = text.replace(/(.*)(ex)(.*)/gi,'$1<em>$2</em>$3');");
console.log(text)   //text -> t<em>ex</em>t

but

var textx = text.replace("/(.*)(ex)(.*)/gi",'$1<em>$2</em>$3');
console.log(textx) //textx -> text

I've looked at the documentation https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/eval but can't find an explanation.

Thanks

redochka
  • 12,345
  • 14
  • 66
  • 79
  • 3
    Note that the `console.log` in your second code tries to print out a different variable, instead of `textx`. – poke Mar 12 '11 at 15:48

2 Answers2

2
var text = "text";
var textx = text.replace(/(.*)(ex)(.*)/gi,'$1<em>$2</em>$3'); 
console.log(textx) //textx -> text

the problems was that you used a string in the regular expression. "/(.*)(ex)(.*)/gi" -> /(.*)(ex)(.*)/gi

and you had a spelling mistake in the console.log(testx) -> console.log(textx)

Gergely Fehérvári
  • 7,811
  • 6
  • 47
  • 74
2

Because the first uses a regex to match text and the second uses a string.

There is no "/(.*)(ex)(.*)/gi" inside "text". There is /(.*)(ex)(.*)/gi.

sidyll
  • 57,726
  • 14
  • 108
  • 151