html escape (v2)

Revision 2 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

Revisions

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