0

I have a specific div that cannot have tags within it. Whenever tags are found, I would like to escape them and display as regular text.

For example:

<div class='no-tags-div'>
   <h1>Hi!</h1>
   <p>Blablablabalablal</p>
</div>

Instead of displaying the Hi! as a header text followed by a paragraph of Blablablabalablal, I would like to literally display it with the tags:

<h1>Hi!</h1>
<p>Blablablabalablal</p>

I already have access to the content I just need to figure out how to escape any of these special characters.

Edit: I should probably specify, the content within the div is posted through an input. I am attempting to not allow users to post other tags through the input, so this isn't just static HTML text we are talking about here.

theJuls
  • 6,788
  • 14
  • 73
  • 160
  • You can use `element.innerText`. – D. Pardal Apr 16 '20 at 15:23
  • To anybody who stumbles upon this, I found the solution by using the follow npm package: https://www.npmjs.com/package/escape-html. It was deleted for some reason, but I think it is helpful for anyone else who has this issue. – theJuls May 28 '20 at 15:49

1 Answers1

1

You can use &lt; and &gt; to escape < and >. If you're doing this on the server side, you can find and replace those. On the client, you can use element.innerText, as D. Pardal suggested, which replaces the contents of element with a text node, rather than interpreting it as HTML.

crimson_penguin
  • 2,728
  • 1
  • 17
  • 24