2

The code I have currently produces a html page with with "ac" on it, what I want is to have literally what the value of the string is (I would type it out here but I'm having the same problem). In words, what I want is "a" then the less than symbol then "b" then the greater than symbol then "c".

Thanks

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

<script>

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

</script>

</body>
</html>
Mathew
  • 1,116
  • 5
  • 27
  • 59

2 Answers2

6

Set it as text instead of as html

document.getElementById("output").textContent = "a<b>c"
<p id="output"></p>

Or convert to html entities

 var str = "a<b>c".replace('<','&lt;').replace('>','&gt;')
 document.getElementById("output").innerHTML = str;
<div id="output"></div>
charlietfl
  • 170,828
  • 13
  • 121
  • 150
  • `.replace('<','<').replace('>','>')` will only replace the first occurences of each tag. Need to use RegEx instead (see @Mamum's answer below). – Lionel Jan 04 '19 at 10:24
  • 1
    use replaceAll to replace all instances of occurence. – SimpleGuy May 10 '21 at 13:25
4

Try the following way:

document.getElementById("output").innerHTML = "a<b>c".replace(/</g, '&lt;').replace(/>/g, '&gt;')
<div id="output"</div>
Mamun
  • 66,969
  • 9
  • 47
  • 59