htmlEncodeStringReplacement (v61)

Revision 61 of this benchmark created on


Setup

var html = document.body.innerHTML;
  var map = {
    "&": "&",
    "'": "'",
    '"': """,
    "<": "&lt;",
    ">": "&gt;"
  };
  
  function replaceEntity(chr) {
    return map[chr];
  }
  
  String.prototype.replaceAll = function(str1, str2, ignore) {
    return this.replace(new RegExp(str1.replace(/([\/\,\!\\\^\$\{\}\[\]\(\)\.\*\+\?\|\<\>\-\&])/g, "\\$&"), (ignore ? "gi" : "g")), (typeof(str2) == "string") ? str2.replace(/\$/g, "$$$$") : str2);
  };
  String.prototype.htmlEncode = function() {
    return this.replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/'/g, '&#39;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
  };
  var re_amp = /&/g;
  var re_squo = /'/g;
  var re_dquo = /"/g;
  var re_lt = /</g;
  var re_gt = />/g;
  
  
  function charsReplace(str) {
    var result = '';
    for (var i = 0, len = str.length; i < len; ++i) {
      var c = str.charAt(i);
      switch (c) {
        case '&':
          result += '&amp;';
          break;
        case '"':
          result += '&quot;';
          break;
        case '\'':
          result += '&#39;';
          break;
        case '<':
          result += '&lt;';
          break;
        case '>':
          result += '&gt;';
          break;
        default:
          result += c;
      }
    }
    return result;
  };

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
charsReplace
return charsReplace(html);
ready
predefined regexp literals
return html.replace(re_amp, '&amp;').replace(re_dquo, '&quot;').replace(re_squo, '&#39;').replace(re_lt, '&lt;').replace(re_gt, '&gt;');
ready
string replaceAll method
return html.replaceAll('&', '&amp;').replaceAll('"', '&quot;').replaceAll("'", '&#39;').replaceAll('<', '&lt;').replaceAll('>', '&gt;');
ready
replace chain on prototype
return html.htmlEncode();
ready
single replace with pre-defined function
return html.replace(/[&"'\<\>]/g, replaceEntity);
ready

Revisions

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