htmlEncodeRegEx (v20)

Revision 20 of this benchmark created by Prestaul on


Preparation HTML

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>

Setup

var html = document.body.innerHTML;
  var map = {
    "&": "&amp;",
    "'": "&#39;",
    '"': "&quot;",
    "<": "&lt;",
    ">": "&gt;"
  };
  var tempElement = $(document.createElement("div"));
  var div = document.createElement('div');
  var text = document.createTextNode();
  div.appendChild(text);

Test runner

Ready to run.

Testing in
TestOps/sec
multiple replace()
return html.replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/'/g, '&#39;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
ready
single replace with map
return html.replace(/[&"'\<\>]/g, function(c) {
  return map[c];
});
ready
single replace with switch
return html.replace(/[&"'\<\>]/g, function(c) {
  switch (c) {
  case "&":
    return "&amp;";
  case "'":
    return "&#39;";
  case '"':
    return "&quot;";
  case "<":
    return "&lt;";
  case ">":
    return "&gt;";
  }

});
ready
use jQuery
return $('<div/>').text(html).html();
ready
use jQuery with pre-created element
return tempElement.text(html).html();
ready
multi split/join
return html
	.split('&').join('&amp;')
	.split('"').join('&quot;')
	.split("'").join('&#39;')
	.split('<').join('&lt;')
	.split('>').join('&gt;');
ready
native DOM technique
text.nodeValue = html;
return div.innerHTML;
ready

Revisions

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