userimage
Moe

How to encode a string HTML using javascript

I have a string HTML and before sending to server i want to encrypt that HTML as below

var str = '<tag>data</tag>';

to '&lt;tag&gt;data&lt;&#39;tag&gt;'


Basically i want a common method that will help me to parse the string to encoded string so that if i will get the same from server to client it will display to user like a simple html as a text without executing the string html.

userimage

you can try a very common method to parse the same, i mean the string html to encoded string. Use below code to do so

function encodeHTML(strHTML) {
	return strHTML.replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/'/g,
			'&#39;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
}
Answer is