You should not try to escape from HTML, the content of comments is not escaped, and this is normal if you have bare 'or' & inside.
'is its own, unrelated problem and is not really fixable. If you do not need to restore the exact string, just replace it to get rid of them (for example, replace with "__").
If you need to get a string that is completely non-JavaScript that will read the contents of a comment, use a string literal:
which can then read the script using eval (commentnode.data). (Yes, the actual use for eval () is finally!)
Then your escaping problem is how to put things in JS string literals, which is pretty easily resolved by escaping the "and" characters:
(You should probably also avoid "<," & and "if you ever want to use the same escaping scheme to place a JS string literal inside a <script> block or inline handler.)
source share