Escape </ in script tag contents

I came here looking for a way to universally escape </script> inside the JavaScript code.

After bit of research I figured that if you are trying to escape </script> in JavaScript code so it can be safely embedded in html between <script> and </script> tags you should replace </script with </scr\ipt or </scri\pt. It's safer to do because if you replace it with <\/script you might break JavaScript code like this: var q = -1</script/.test("script");

Be careful not to look for </script> but rather </script because </script asdasdas> will end your script just as well as </script> does.

Sorry, it doesn't help OP in any way. Accepted answer is absolutely correct that you need to know what constructs are legal in language you have inside your <script></script> to know how to escape </script> occurrence without braking the code.


In HTML, as opposite to XHTML, the content of a script element is processed as plain text except for the occurrence of an end tag, so that </ ends processing and must, in conforming documents, start the end tag </script>. There is no general mechanism to avoid this. Any methods that circumvent this feature are unavoidably dependent on the “language” used inside the element. The word “language” is in quotes here, because the content can be just about anything, as long as your code can parse and process it.

So: no general mechanism, but for content other than JavaScript or some of the few other client-side scripting languages recognized by some browsers, you can make your own rules.


The HTML specification explains in detail what is allowed and how to securely escape content. Especially considering HTML's history, this is a non-trivial task.

From the HTML specification:

The easiest and safest way to avoid the rather strange restrictions described in this section is to always escape "&lt;!--" as "&lt;\!--", "&lt;script" as "&lt;\script", and "&lt;/script" as "&lt;\/script" when these sequences appear in literals in scripts (e.g., in strings, regular expressions, or comments), and to avoid writing code that uses such constructs in expressions. Doing so avoids the pitfalls that the restrictions in this section are prone to triggering: namely, that, for historical reasons, parsing of script blocks in HTML is a strange and exotic practice that acts unintuitively in the face of these sequences.

Source: https://www.w3.org/TR/html52/semantics-scripting.html#restrictions-for-contents-of-script-elements

Tags:

Html