简体   繁体   中英

How to escape HTML special characters in Javascript

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM