How to safely convert / parse HTML and other symbols to simple text?

I have a chat application developed using NodeJs and HTML. Now, all I want that if I type something like:

  1. Hi > how?
  2. <div style="color:red"></div>
  3. & could you

All of them should be displayed as they are. And HTML tags shouldn't be rendered and text shouldn't be red. In short, the output should be like:

  1. Hi > how?
  2. <div style="color:red"></div>
  3. & could you

I looked for some old questions and answers here, but I want to know how major sites like Facebook, WhatsApp, Quora do such things? Just like converting > and < to &lt and &gt or using a method like replace()?

1 answer

  • answered 2017-06-17 18:44 James Douglas

    You can use the <xmp> tag. Everything inside it will be plain text, rather than HTML.

    <xmp><div style="color:red">hi</div></xmp>

    Alternatively, you could use the <plaintext> tag, but that doesn't have a close tag, so would be annoying to use.

    <plaintext><div style="color:red">hi</div></plaintext>


    You can use some JavaScript and jQuery to achive this:

    var text = $('.container').html();
    <script src=""></script>
    <div class="container"><div style="color:red">hi</div></div>

    This grabbs the html inside the .container div, and converts it to plain text.