Thursday, July 23, 2015

JavaScript Function: HTML Encode for Multiple Lines Of Text Sharepoint

Recently I have found the need to HTML Encode text in JavaScript, especially when using update list items and Single Line Of Text or Multiple Lines Of Text fields.
An easy way to do this is use the native functionality of the browser when it processes DIV’s.
Any text inside of a DIV automatically gets HTML Encoded.  So all we have to do is create a DIV on the fly, insert the text and return the output.
1 function HTMLEncode(str) { 2 var div = document.createElement('div'); 3 var text = document.createTextNode(str); 4 div.appendChild(text); 5 return div.innerHTML; 6 }