How to put "</script>" in a javascript string?

13,707

it is because of the \ I believe. i have no concrete explanation since I am a newbie to Javascript but this code should work:

alert("<script><\/script>");

came up with it using Java knowledge.. Haha since the \ is an escape key in many languages.

Share:
13,707

Related videos on Youtube

Victor2748
Author by

Victor2748

8+ Years of experience. Currently a student at University of Toronto, studying Computer Science Specialist with focus in Artificial Intelligence + Economics Major + Statistics Minor

Updated on September 16, 2022

Comments

  • Victor2748
    Victor2748 over 1 year

    I've been trying some tricks in javascript and came to a ridiculous problem: I can't use <script> as a substring in a javascript string! Here is an example:

    <html>
        <head>
            <script>
                alert("<script></script>");
            </script>
        </head>
    </html>
    

    It supposed to print out <script></script>, but instead, I get this:

    ");
    

    Printed out on the page, as HTML.

    Question: How can I use <script> followed by </script> substrings in Javascript, and why is it acting that way?

    Here is JSFiddle of it.