How to render js output ignoring html tags?

  • 0
    There is such a script in the chats
    else {
            var text = '<div class="card"><p>'+data.content+'</p></div>';

    data.content gets from json (django backend). The text of the message is inserted into this place, but the problem is that all this is written in a line with html tags, that is, any user can insert tags (for example, by writing & lt; b & gt; Bold & lt; / b & gt; comes the text " Bold " in bold, respectively), or even a whole script that can break everything. It is necessary to somehow get around this moment. I had a suggestion that something like this should be done
    	let test = $('<div style="font-size:24px;"></div>');
     	let test1 = $('<div style="background: #000;"></div>');
     	let test2 = $('<div style="color: #fff;"></div>');
      test2.text('<div style="color:red">test</div>');

    That is, insert a tag into a tag, and so on. But I have 10 of these divs plus 3 checks, that is, about 90 lines of code will be added in such a way that it does not suit me. Can you advise on a more elegant way to work around this problem?
    JavaScript Anonymous, Feb 22, 2020

  • 2 Answers
  • 0
    Backing should clear the string from html entities.

    Here an example of a similar function from WordPress

    If you really need to, you can do the same at the front: / can-i -...
    Julia Mason

  • 0
    this is xss

    validate necessarily on the back, or there will be a moment when someone breaks your site
    Zachary Villa

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!