user5346990
user5346990

Reputation:

Print html text with tag in new window

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!

Upvotes: 0

Views: 202

Answers (2)

victor
victor

Reputation: 1552

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.

Upvotes: 1

IsaacDorenkamp
IsaacDorenkamp

Reputation: 61

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.

Upvotes: 0

Related Questions