[英]javascript replace fails to work with “<”
I am trying to replace "<"
and ">"
in a string using javascript's replace function. 我正在尝试使用javascript的replace函数替换字符串中的"<"
和">"
。 I am using it as follows: 我使用它如下:
<html> <body onload="myFunction()"> <p id="demo">#include <iostream></p> <script> function myFunction() { var str = document.getElementById("demo").innerHTML; var res = str.replace(/</g, '< ').replace(/>/g, '> '); document.getElementById("demo").innerHTML = res; } </script> </body> </html>
I expect the output to be "#include <iostream>"
, but a corresponding </iostream>
is appended to the desired output. 我希望输出为"#include <iostream>"
,但是</iostream>
相应的</iostream>
附加到所需的输出中。
What is going on? 到底是怎么回事? How do I avoid this behaviour? 我如何避免这种行为?
Because you have <iostream>
in your html, it is being interpreted as a tag in your browser which adds an extra closing </iostream>
. 因为您的html中有<iostream>
,所以它在浏览器中被解释为标记,从而添加了额外的结束</iostream>
。 It looks as if you're trying to escape it using JS, but it's too late because your browser is loading the html before the javascript, adding the extra closing tag. 似乎您正在尝试使用JS对其进行转义,但为时已晚,因为您的浏览器在javascript之前加载了html,并添加了额外的结束标记。 Escape it in your html to avoid the extra closing tag being appended behavior: 在您的html中转义它,以避免附加的结束标记被附加为行为:
<p id="demo">#include <iostream></p>
I just want to automate the replacement of "<" and ">" with
<
我只想用<
自动替换“ <”和“>”<
and>
和>
respectively. 分别。 @rioc0719: I don't want to do manual replacement.` @ rioc0719:我不想手动更换。
Please don't try to do this with JS. 请不要尝试使用JS执行此操作。 Get an IDE that does it for you. 获取为您执行此操作的IDE。 Hell, make a server-side script that does this for you; 该死,制作一个服务器端脚本来为您完成此任务; just don't use JS, a client-side language, for this. 只是不要为此使用客户端语言JS 。
2 answer in question 2个问题的答案
<html> <body onload="myFunction()"> <p id="demo">#include <iostream> </p> <script> function myFunction() { var str = document.getElementById("demo").innerHTML; var res = str.replace(/</g, '< ').replace(/>/g, '> '); document.getElementById("demo").textContent = res; } </script> </body> </html>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.