The browser does not understand that the script tag in the alert is not the closing tag.
Instead of looking at the html code, lets look at some JavaScript.
Your problem is equivalent to
See the issue there? We want the whole
string, but it chops it off early at the ' after Eric and throws an error. In the case of the HTML it stops it at the script tag in the code and than renders whatever else as text on the page.
So how would be fix the JavaScript example? We would escape the '
And it would work fine.
What we need to do for the HTML issue is to break up the script tag into two parts.
The browser will no longer see the closing script tag when it is rendering the page.
Eric