0

I have a snippet of code kinda/sorta like this:

<script>
var foo = "<span>Hello <script>var bar = 1;</script> world</span>" ;
</script>

This barfs and displays and renders the span. The problem is caused by the " value in the variable.

I have worked around it by escaping the \ and changing it to

<script>
var foo = "<span>Hello <script>var bar = 1;<\/script> world</span>" ;
foo.replace("\/script", "/script") ;
</script>

This works fine. This seems really, really hokey. There has to be a better way to do this??

WonFineDay
  • 77
  • 1
  • 8

1 Answers1

0

How about this?

var foo = "<span>Hello " + "<script>var bar = 1;<\/script>" + " world</span>";
$('body').append(foo);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
cssyphus
  • 37,875
  • 18
  • 96
  • 111
  • Downvoted because . . . ? – cssyphus Mar 30 '16 at 21:58
  • It's not my downvote, but I'm guessing it's because it introduces an unnecessary dependency on jQuery to do something incredibly trivial. – Chris Mar 30 '16 at 22:58
  • Odd. The OP specified jQuery and he used jQuery in his question. Anyway, thanks for the note. – cssyphus Mar 30 '16 at 23:24
  • Oh. I didn't notice it was a tag. I don't see it actually used anywhere in the question though. No idea what the downvote was for then. – Chris Mar 30 '16 at 23:26