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

1
  • 3
    Note that the console.log in your second code tries to print out a different variable, instead of textx. Commented Mar 12, 2011 at 15:48

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.