Encoding HTML Entities with Javascript

By Nick Little on June 18, 2008 at 6:23 pm in Technical

Today I needed to use a bit of javascript to modify the contents of a web page. However, the section of the page I was changing was being updated with user entered content. I wanted the content on the page to show exactly what the user typed, meaning that I had to make sure that if the user entered any valid xhtml code it was encoded correctly. I searched around on google and found next to nothing on the topic, so I decided to create my own.

I used the php function “htmlspecialchars” as the basis for my function. I looked up the replacements that this functions uses. It turns out that only four characters need to be replaced to properly encode the contents: &, <, >, and “. Here is the function:

function htmlEncode(str) {
  return str.replace(/&/g, '&amp;').replace(/"/g, '&qout;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
}

The only thing I had to watch was that the ampersand character was encoded before the others, since it is used for encoding the others.