Hello Body"; I wa...">

Print html tags in javascript

Thank you for reading!

var data = "<html><head><title>Hello</title></head><body>Hello Body</body></html>"; 

I want to print data , including HTML tags, without displaying the browser HTML tags and just displaying "Hello Body".

I tried:

str = str.replace("<", "");

but in vain.

+4
source share
3 answers
  data = data.replace(/</g, "&lt;").replace(/>/g, "&gt;"); 

When the browser encounters &lt; (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.

+11
source

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; } 
+9
source

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,'&amp;') .replace(/</g,'&lt;') .replace(/>/g,'&gt;'); document.write(data); 

Of course, creating a little helper function would be better.

+3
source

Source: https://habr.com/ru/post/1347629/


All Articles