1

I am developing a web application. In my javascript I have my code like this:

var x = '<p> This is a paragraph</p> <h1> Heading</h1> ";

I want to convert this into proper html text like this:

<p> This is a paragraph</p> <h1> Heading</h1>

Is there any javascript function for doing that so that when I console log it, it appears as proper html text?

Any suggestions will be highly appreciated.

sshussain270
  • 1,785
  • 4
  • 25
  • 49
  • This is probably the solution you are looking for: http://stackoverflow.com/a/20880789/395910 – Terry Nov 06 '16 at 23:26

1 Answers1

0

You can assign this to the innerHtml property of an DOM element.

However, doing so has its host of risks associated to it, so use with caution. Specifically, if this is some data/text that comes from users, they could inject script tags and execute anything in the context of your app, which would be a huge security risk for your app.

Lucero
  • 59,176
  • 9
  • 122
  • 152
  • I am not trying to display it in a web page. I am trying to console log it, can you please clarify a bit using code what you are trying to say? – sshussain270 Nov 06 '16 at 23:23
  • It is obviously escaped HTML. So set the `innerHtml` and then write out the `textContent` to the console and you're done. The element doesn't have to be visible/attached. – Lucero Nov 06 '16 at 23:25
  • @Elisha512, what for do you need HTML markup in console.log? – aring Nov 06 '16 at 23:25
  • 1
    What you have is HTML entities, and you have to parse those. You can either write your own parser, or you can let the browser do it for you. If you want to do the latter, you have to put that string in the DOM as HTML, and then get it back again, as it will be parsed by that time – adeneo Nov 06 '16 at 23:25
  • People can also open the console and write any JavaScript they wish. – Spencer Wieczorek Nov 06 '16 at 23:25
  • @SpencerWieczorek Sure, but it is not the same whether the user sitting on the computer hacks code into the console or if data coming from a server executes stuff in *your* console... look up [XSS attack](https://en.wikipedia.org/wiki/Cross-site_scripting). – Lucero Nov 06 '16 at 23:28