Html Escaping (v3)

Revision 3 of this benchmark created on


Description

Testing various ways of html escaping a string

Preparation HTML

<script>
  var testString = '<scr' + 'ipt>alert("Not escaped")</' + 'script>';
  var tmp = document.createElement("b");
  var escapeCache = {
   "&": "&amp;",
   "\\": "\\\\",
   '"': '\"',
   "<": "&lt;",
   ">": "&gt;"
  };

var escapeHTML = (function () {
    var controlChars = /["'<>&]/g;

    var encodedChars = {
        '&': '&amp;',
        '"': '&quot;',
        '\'': '&#39;',
        '<': '&lt;',
        '>': '&gt;'
    };
    function encodeChar(char) {
        return encodedChars[char];
    }

    return function (rawTxt) {
        return rawTxt.replace(controlChars, encodeChar);
    };
})();
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
Using a regex
testString.replace(/[\&"<>\\]/g, function(s) {
 switch (s) {
 case "&":
  return "&amp;";
 case "\\":
  return "\\\\";
 case '"':
  return '\"';
 case "<":
  return "&lt;";
 case ">":
  return "&gt;";
 default:
  return s;
 }
});
ready
User in DOM nodes
tmp.innerHTML = ""
tmp.appendChild(document.createTextNode(testString));
tmp.innerHTML;
ready
Using a regex + cache
testString.replace(/[\&"<>\\]/g, function(s) {
 return escapeCache[s] || s;
});
ready
escapeHTML
escapeHTML(testString);
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.