1

Take the code below: it obviously fails because the </script> tag in the string literal is not escaped.

<script>
var myquestion = "What is the tag used to mark the end of a Javascript section?";
var myanswer = "It's </script>!";
alert(myanswer.length);

function someMoreCode() {
    // ...
}
</script>

However if I do escape it as shown below, the string variable now contains the literal It's &lt;/script>, not It's </script>:

<script>
var myquestion = "What is the tag used to mark the end of a Javascript section?";
var myanswer = "It's &lt;/script>";
alert(myanswer.length);

function someMoreCode() {
    // ...
}
</script>

The popup box will show 17 instead of the expected 14 which is the length of the string It's </script>.

How can I define a string to have the contents It's </script>?

I would like a generic method that can be applied to any string as the actual string contents will be coming from user provided data stored in a database, so doing something like "<"+"/script" wouldn't be suitable.

Laurent
  • 5,953
  • 14
  • 43
  • 59

1 Answers1

2

You can escape the slash using a backslash:

<script>
    var myquestion = "What is the tag used to mark the end of a Javascript section?";
    var myanswer = "It's <\/script>!";
    console.log(myanswer);
    
    function someMoreCode() {
        // ...
    }
</script>

(alert replaced with console.log for demonstration purposes)

Donald Duck
  • 8,409
  • 22
  • 75
  • 99
Ethan
  • 3,410
  • 1
  • 28
  • 49