Print html tags in javascript
data = data.replace(/</g, "<").replace(/>/g, ">"); When the browser encounters < (which is known as the symbol object), it will replace it with the literal '<', allowing you to display HTML tags on the page without rendering them.
/</g is a regular expression that simply says βmatch all" <in a string, "and g means doing it globally. Without g it will replace only the first '<' it encounters.
One final note: itβs better to use a library such as jQuery. This is the material that easily makes mistakes and misses cases. Let the hardened, well-tested and safe library feature do it for you.
The actual (and safer fix) is as follows:
function htmlspecialchars(text){ return jQuery('<div/>').text(text).html(); } In pure javascript, this will be:
function htmlspecialchars(text){ var tnd=document.createTextNode(text); var div=document.createElement("DIV"); div.appendChild(tnd); return div.innerHTML; } This is ugly, but you can try this (borrowed from the Prototype escapeHTML() implementation):
var data = "<html> <head> <title> Hello </title> </head> <body> Hello Body </body> </html>" .replace(/&/g,'&') .replace(/</g,'<') .replace(/>/g,'>'); document.write(data); Of course, creating a little helper function would be better.