转义javascript中的大于和小于符号

Mat*_*hew 0 javascript

我目前使用的代码生成了一个带有“ac”的 html 页面,我想要的是字面上的字符串值是什么(我会在这里输入它,但我遇到了同样的问题)。换句话说,我想要的是“a”,然后是小于符号,然后是“b”,然后是大于符号,然后是“c”。

谢谢

<!DOCTYPE html>
<html>
<body>
<p id="output"></p>

<script>

document.getElementById("output").innerHTML = "a<b>c"

</script>

</body>
</html>
Run Code Online (Sandbox Code Playgroud)

cha*_*tfl 6

将其设置为文本而不是 html

document.getElementById("output").textContent = "a<b>c"
Run Code Online (Sandbox Code Playgroud)
<p id="output"></p>
Run Code Online (Sandbox Code Playgroud)

或者转换为html实体

 var str = "a<b>c".replace('<','&lt;').replace('>','&gt;')
 document.getElementById("output").innerHTML = str;
Run Code Online (Sandbox Code Playgroud)
<div id="output"></div>
Run Code Online (Sandbox Code Playgroud)


Mam*_*mun 6

尝试以下方法:

document.getElementById("output").innerHTML = "a<b>c".replace(/</g, '&lt;').replace(/>/g, '&gt;')
Run Code Online (Sandbox Code Playgroud)
<div id="output"</div>
Run Code Online (Sandbox Code Playgroud)