Home > Web Front-end > JS Tutorial > 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
Release: 2024-10-24 11:23:02
Original
261 people have browsed it

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>
Copy after login

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>......';
Copy after login

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!

source:php
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template