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
.
How do you use escape in JavaScript?
The escape() function computes a new string in which certain characters have been replaced by a hexadecimal escape sequence. Note: This function was used mostly for URL queries (the part of a URL following ? ) —not for escaping ordinary String literals, which use the format \xHH .
Where do I put script tag in JavaScript?
The browser loads all the scripts included in the <head> tag before loading and rendering the <body> tag elements. So, always include JavaScript files/code in the <head> that are going to be used while rendering the UI. All other scripts should be placed before the ending </body> tag.
How do I reference a JavaScript script?
Save the script file with a .js extension, and then refer to it using the src attribute in the <script> tag. Note: The external script file cannot contain the <script> tag. Note: Point to the external script file exactly where you would have written the script.
Can we use script tag in JavaScript?
The <script> tag is used to embed a client-side script (JavaScript). The <script> element either contains scripting statements, or it points to an external script file through the src attribute.
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>
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.