Reputation:
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
Reputation: 1552
If you html encode your string so that symbols like <
become <
, it will work.
document.write("<h1>");
will print <h1>
.
By the way, jQuery`s text() function does this for you.
function escapeHtml(unsafe) {
return unsafe
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
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
Reputation: 61
Convert all the html characters to entities, possibly, like this:
str = str.replace('&', '&').replace('<', '<').replace('>', '>');
Order does not matter EXCEPT that the ampersand replace MUST BE FIRST or else it will create strange behavior.
Upvotes: 0