html escape (v4)

Revision 4 of this benchmark created on


Setup

const markup = "<span>Hello, World!</span>";

const replacer = (match) => {
  if (match === "&") return "&amp;";
  else if (match === "<") return "&lt;";
  else if (match === ">") return "&gt;";
  else if (match === "'") return "&apos;";
  else if (match === '"') return "&quot;";
};

const replacer2 = (match) => {
  switch (match) {
    case "&":
      return "&amp;"; break;
    case "<":
      return "&lt;"; break;
    case ">":
      return "&gt;"; break;
    case "'":
      return "&apos;"; break;
    case '"':
      return "&quot;"; break;
  }
};

Test runner

Ready to run.

Testing in
TestOps/sec
replaceAll replaceAll replaceAll
markup.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll("'", "&apos;").replaceAll("\"", "&quot;");
ready
replace replace replace w/ regex
markup.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/'/g, "&apos;").replace(/"/g, "&quot;");
ready
single replace w/ regex & callback
markup.replace(/[&<>'"]/g, replacer);
ready
replace w/ regex & switch callback
markup.replace(/[&<>'"]/g, replacer2);
   
ready
Not chained replaceAll
markup.replaceAll("&", "&amp;");
markup.replaceAll("<", "&lt;");
markup.replaceAll(">", "&gt;");
markup.replaceAll("'", "&apos;");
markup.replaceAll("\"", "&quot;"); 
ready
Not chained replace
markup.replace(/&/g, "&amp;");
markup.replace(/</g, "&lt;");
markup.replace(/>/g, "&gt;");
markup.replace(/'/g, "&apos;");
markup.replace(/"/g, "&quot;"); 
ready

Revisions

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