Reputation: 15
I am trying to replace "<"
and ">"
in a string using javascript's replace function. 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.
What is going on? How do I avoid this behaviour?
Upvotes: 0
Views: 173
Reputation: 746
2 answer in question
<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>
Upvotes: 0
Reputation: 13809
Because you have <iostream>
in your html, it is being interpreted as a tag in your browser which adds an extra closing </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. Escape it in your html to avoid the extra closing tag being appended behavior:
<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.`
Please don't try to do this with JS. Get an IDE that does it for you. Hell, make a server-side script that does this for you; just don't use JS, a client-side language, for this.
Upvotes: 1