Encode HTML entities (v2)

Revision 2 of this benchmark created on


Preparation HTML

<script>
  var test = 'if (a < b && c > d) {} // Héllö naõ';
  
  function safe_tags_regex(str) {
   return str.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
  }
  
  function safe_tags_dom(str) {
   var div = document.createElement('div');
   div.appendChild(document.createTextNode(str));
   return div.innerHTML;
  }
  
  var tagsToReplace = {
   '&': '&amp;',
   '<': '&lt;',
   '>': '&gt;'
  };
  
  function replaceTag(tag) {
   return tagsToReplace[tag] || tag;
  }
  
  function safe_tags_replace(str) {
   return str.replace(/[&<>]/g, replaceTag);
  }
  
  
  function safe_tags_simplereplace(str) {
   return str.replace('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;');
  }
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
Using Regular Expression
test = safe_tags_regex(test);
ready
Using DOM textNode
test = safe_tags_dom(test)
ready
Using replace
test = safe_tags_replace(test)
ready
Using simple replace
test = safe_tags_simplereplace(test)
ready

Revisions

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