Script tag in JavaScript string
What happens?
The browser HTML parser will see the </script>
within the string and it will interpret it as the end of the script element.
Look at the syntax coloring of this example:
<script>
var test = 'foo... </script> bar.....';
</script>
Note that the word bar is being treated as text content outside of the script element...
A commonly used technique is to use the concatenation operator:
var test = '...... </scr'+'ipt>......';
/script within a JavaScript string in a script tag
The HTML parses it as:
<script type="text/javascript">
alert("hello
</script>
");
</script>
With the first occurrence of </script>
closing the open <script>
element. The common way of avoiding this issue is by including a \
before the /
character in the string:
<script type="text/javascript">
alert("hello <\/script>");
</script>
This works because the \
escape character will prevent the browser from recognizing <\/script>
as an end tag. Normally \
is used as an escape sequence in JavaScript strings, but as there's no \/
sequence, the escape character is ignored and the string evaluates as '</script'>
.
This issue can generally be avoided if you follow the good practice of keeping all of your javascript in external .js
files. That said, it's common to see this sort of escaping used for local script fallbacks for unresponsive CDNs.
Load script tag as a string and append it to html header
With Jquery,
var httpResponseMock = '<script><\/script>';
$('head').append(httpResponseMock);
and with javascript
var httpResponseMock = '<script><\/script>';
document.getElementsByTagName('head')[0].appendChild(httpResponseMock);
How to include an escapedscript /script tag in a JavaScript variable?
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.
How can I load script tags from a string?
The second example runs because you 're using a dom node. That 's how appendChild()
works. The jQuery get()
method works with existing dom elements. The only thing you 've got is a string, that does not exist in your dom yet. Try the following.
let script = $.parseHtml(sLoadThis);
console.log(script.get(0)); // should be a script dom node element
document.head.appendChild(script.get(0));
In vanilla JavaScript its even easier and much more faster than jQuery because you don 't have to use a dependency.
const fragment = document.createRange().createContextualFragment(htmlStr);
document.head.appendChild(fragment);
How to put /script in a javascript string?
What's tripping you up is the </script>
. The HTML parser doesn't recognize Javascript strings or nested <script>
tags, so it's interpreting that as the closing tag for the initial <script>
. That is, this part of the document is parsed as:
<script> (open tag)
alert("<script> (text node - contents of the script)
</script> (close tag)
"); (text node - plain text)
The second </script>
is ignored, as there's no other <script>
tag for it to close.
To work around this, break up </script
so that the HTML parser doesn't see it. For instance:
alert("<script><\/script>");
or:
alert("<script><" + "/script>");
or just put the code in an external Javascript file. This issue only arises for inline scripts.
String doesn't accept the close tag for /script
You need it to break the </script>
into "<" + "/script>"
so that the HTML parser doesn't interpret it as the closing tag. You can also do <\/script>
.
An example of how it works:
<script>
console.log("hello <\/script>");
console.log("hello <" + "/script>");
</script>
Is script tag inside javascript string object currently forbidden?
You can do it like this:
let textValue='<script>content<\/script>';
console.log(textValue);
Related Topics
Determine Original Name of Variable After Its Passed to a Function
What Is the Correct Way to Check for String Equality in JavaScript
JavaScript Require() Function Giving Referenceerror: Require Is Not Defined
Why Does (0 < 5 < 3) Return True
How to Convert HTML to JSON Using PHP
JavaScript - Head, Body or Jquery
JavaScript Filereader - Parsing Long File in Chunks
How to Prevent Submitting the HTML Form's Input Field Value If It Empty
Access Event to Call Preventdefault from Custom Function Originating from Onclick Attribute of Tag
5Xx or 4Xx Error with "No 'Access-Control-Allow-Origin' Header Is Present"
What Are the Differences Between Deferred, Promise and Future in JavaScript
Why Is JavaScript Bind() Necessary
How to Do a Horizontal Scroll on Mouse Wheel Scroll