Thanks for reading!
var data = "<html><head><title>Hello</title></head><body>Hello Body</body></html>";
I want to print data
including the HTML tags without having the browser rendering the HTML tags and just displaying "Hello Body".
I tried:
str = str.replace("<", "");
but in vain.
data = data.replace(/</g, "<").replace(/>/g, ">");
When the browser encounters <
(which is known as a character entity), it will replace it with a literal '<', enabling you to display the HTML tags on the page without them getting rendered.
/</g
is a regular expression that just says "match all '<' in the string", and g
means do it globally. Without the g
it will only replace the first '<' it encounters.
And one final note, it's much better to use a library, such as jQuery, to do this. This is the kind of stuff that is easy to get wrong and miss edge cases on. Let the hardened, well tested and secure library function do it for you.