Home  >  Article  >  Web Front-end  >  How to Prevent Unexpected Script Termination from Closing Script Tags Embedded in JavaScript Strings?

How to Prevent Unexpected Script Termination from Closing Script Tags Embedded in JavaScript Strings?

Barbara Streisand
Barbara StreisandOriginal
2024-10-24 11:23:02130browse

How to Prevent Unexpected Script Termination from Closing Script Tags Embedded in JavaScript Strings?

Script Termination within JavaScript Strings

In JavaScript, embedding a closing script tag () inside a quoted string can cause unexpected script termination. This occurs when the browser's HTML parser interprets the tag within the string as the end of the script element.

For example, in the following code snippet:

<script>
var test = 'foo... <\/script> bar.....';
</script>

The closing script tag within the string terminates the script element prematurely, resulting in the "bar" portion of the string being treated as text content outside the script block.

To circumvent this issue, one common technique is to use the concatenation operator ( ) to concatenate the string segments:

var test = '...... </scr' + 'ipt>......';

By splitting the script tag into parts and concatenating them, you can prevent the browser from interpreting the closing tag as the end of the script element.

The above is the detailed content of How to Prevent Unexpected Script Termination from Closing Script Tags Embedded in JavaScript Strings?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn