Home > Article > Web Front-end > What is the Impact of Using a Script Tag Inside a JavaScript String and How to Solve It?
Understanding Script Tag in JavaScript String
In JavaScript, using a script tag inside a quoted string can potentially disrupt the execution of the script. This behavior stems from the HTML parser's recognition of in the string as the end of the script element.
Consider the example:
<script> var test = 'foo... </script> bar'; // The script tag in the string confuses the parser </script>
Here, the HTML parser interprets within the string as the conclusion of the script element, causing the execution to halt.
To address this issue, prevent the parser from interpreting in the string as the end of the script element. A common technique is to use string concatenation as follows:
var test = '...... </scr' + 'ipt>......';
By splitting into individual characters and concatenating them, the parser can no longer identify it as the end of the script element, thus allowing the script to execute correctly.
The above is the detailed content of What is the Impact of Using a Script Tag Inside a JavaScript String and How to Solve It?. For more information, please follow other related articles on the PHP Chinese website!