Home > Work > Useful JavaScript Function: HTML Encode #in

Useful JavaScript Function: HTML Encode #in

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 }

Advertisements
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: