Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
141
rated 0 times [  143] [ 2]  / answers: 1 / hits: 15125  / 9 Years ago, sat, february 21, 2015, 12:00:00

I have a string in Javascript where I have to escape several characters:



<script>
function GenerateCode() {
alert(ctry);
var script = <script async src=//somesite.com/feed/livetrend.js></script>;
}
</script>


I have tried the following to escape the characters:



var script = <script async src=//somesite.com/feed/livetrend.js></script>;


However, this does not work correctly, despite having taken care of including an escape character in front of



It an error -unterminated string constant.


More From » javascript

 Answers
10

The issue is that when the browser encounters the closing </script> tag inside a open <script> tag, regardless of the context in which it is used, it will terminate the script tag there. There are a couple of way to avoid this.


Option 1 - Escape the / in the closing script tag:


var script = '<script async src="//somesite.com/feed/livetrend.js"></script>';

Option 2 - Wrap the JavaScript in commented out HTML comments:


<script>
/*<!--*/
var script = '<script async src="//somesite.com/feed/livetrend.js"></script>';
/*-->*/
</script>

Using <![CDATA[ and ]]> instead of <!-- and --> also works.


One potential downside to this might be if you also want to have JavaScript strings that also contain these closing comments or CDATA, then it may not work.


Option 3 - Put the JavaScript into an external file:


Of course, moving the JavaScript into an external file will avoid this issue altogether, though it might not be preferable.


[#67729] Thursday, February 19, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kevonmoisesf

Total Points: 693
Total Questions: 101
Total Answers: 128

Location: Reunion
Member since Mon, Dec 28, 2020
3 Years ago
;