AMP Error Related to Parsing Javascript Strings: Uncaught Error: Attempting to parse invalid HTML content

If your using Javascript to pass an HTML string inside an <amp-script>, chances are you have encountered this error:

Uncaught Error: Attempting to parse invalid HTML content

If you forget to add a forward slash to an HTML closing tag, AMP will complain that you are “Attempting to parse invalid HTML content.” As a result, the following error is generated.

[amp-script] Uncaught Error: Attempting to parse invalid HTML content.
at (amp-script%5Bscript=%22myscript%22%5D.js:1)

But when you do include a forward slash, AMP will complain that you have an “Invalid or unexpected token.”

[amp-script] Uncaught SyntaxError: Invalid or unexpected token
at (blob:https://website.com) This error will occur when you are passing a Javascript string with properly closed HTML tags.

The solution is to escape all HTML tags in your Javascript string. As an example:

myVar = "<div class='myclass'>My text</div>";
// unescaped closing tag: </div>
// escaped closing tag: <\/div>

Of course these errors appear in different situations, but what I have mentioned is a valid cause for generating these errors.