0

I need to print in a new window with a string html tags html. What I did is:

function printNewTab(toPrint, title) {
   var newWin = window.open("about:blank");
   newWin.document.write("<html><head><title>" + title + "</title></head></html>");
   newWin.document.write(toPrint.toString());
   console.log(title + ":");
   console.log(toPrint);
}

but if I have a string like this:

var s = "<h1>title<u> number</u> 1</h1>";

and use the method above:

printNewTab(s, "title");

I obtain a new window where the text does not display tags but is formatted in html.

While I'd really like to see printed <h1>title<u> number</u> 1</h1>. How can I do this?

Thanks!

2 Answers2

1

If you html encode your string so that symbols like < become &lt, it will work.

document.write("&lt;h1&gt;"); will print <h1>.

By the way, jQuery`s text() function does this for you.

function escapeHtml(unsafe) {
    return unsafe
         .replace(/&/g, "&amp;")
         .replace(/</g, "&lt;")
         .replace(/>/g, "&gt;")
         .replace(/"/g, "&quot;")
         .replace(/'/g, "&#039;");
 }

document.write(escapeHtml("<h1>title<u> number</u> 1</h1>"));

This will print <h1>title<u> number</u> 1</h1>.

function taken from this question. Credits to @bjornd.

Community
  • 1
  • 1
victor
  • 1,532
  • 1
  • 13
  • 32
  • Mmm ok, but I'd need something more general because H1 was just an example. The string may be composed of any html tags. –  Nov 07 '15 at 23:53
  • You just create a function to replace all the tags for you. I will add an example – victor Nov 07 '15 at 23:54
0

Convert all the html characters to entities, possibly, like this:

str = str.replace('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;');

Order does not matter EXCEPT that the ampersand replace MUST BE FIRST or else it will create strange behavior.

  • Thanks for the reply but I obtain this error: `Uncaught TypeError: toPrint.replace is not a function`.. –  Nov 07 '15 at 23:52
  • Give me the result of "typeOf toPrint" from the console – IsaacDorenkamp Nov 07 '15 at 23:53
  • Actually, convert toPrint to a string before doing the replace. – IsaacDorenkamp Nov 07 '15 at 23:53
  • I change my code to `function printNewTab(toPrint, title) { var s = toPrint.toString(); console.log("typeOf toPrint: " + toPrint.typeOf); console.log("typeOf s: " + s.typeOf); var newWin = window.open("about:blank"); newWin.document.write("" + title + ""); s = s.replace('&', '&').replace('<', '<').replace('>', '>'); newWin.document.write(s); } ` but results are of typeOf alway `undefined`. There's something wrong in my code.. –  Nov 07 '15 at 23:59
  • 1
    Replace "s.typeOf" with "typeOf s" – IsaacDorenkamp Nov 09 '15 at 14:12