如何在Javascript中转义HTML特殊字符

时间:2017-12-17 11:02:53

标签: javascript

使用下面的代码:它显然失败了,因为字符串文字中的</script>标记未被转义。

<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>

但是如果我如下所示转义它,那么字符串变量现在包含文字It's &lt;/script>,而不是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>

弹出框将显示17而不是预期的14,即字符串It's </script>的长度。

如何定义字符串以包含内容It's </script>

我想要一个可以应用于任何字符串的通用方法,因为实际的字符串内容将来自存储在数据库中的用户提供的数据,因此执行类似"<"+"/script"的操作并不合适。

1 个答案:

答案 0 :(得分:2)

您可以使用反斜杠转义斜杠:

<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替换为console.log用于演示目的)