Regex Replace Benmark

Benchmark created on


Setup

const testStr = "Hello <world> & \"quotes\" \u2028 new line \u2029 done.".repeat(10000);

const forbiddenChars = {
  '<': '\\u003C',
  '>': '\\u003E',
  '"': '\\u0022',
  '&': '\\u0026',
  '\u2028': '\\u2028',
  '\u2029': '\\u2029',
};

const forbiddenRe = /[<>&"\u2028\u2029]/g;

Test runner

Ready to run.

Testing in
TestOps/sec
Variant 1: Regex with external function
// --- Variant 1: Regex with external function

function replaceForbidden(c) {
  return forbiddenChars[c];
}
function escape_regex_func(str) {
  return str.replace(forbiddenRe, replaceForbidden);
}
ready
Variant 2: Regex inline
function escape_regex_inline(str) {
  return str.replace(forbiddenRe, c => forbiddenChars[c]);
}
ready
Variant 3: Loop + string concat
function escape_loop_concat(str) {
  let out = '';
  for (let i = 0; i < str.length; i++) {
    const c = str[i];
    out += forbiddenChars[c] ?? c;
  }
  return out;
}
ready
Variant 4: Loop + array join
function escape_loop_join(str) {
  const out = [];
  for (let i = 0; i < str.length; i++) {
    const c = str[i];
    out.push(forbiddenChars[c] ?? c);
  }
  return out.join('');
}
ready
Variant 5: Regex.test + Regex replace
function escapeForbidden(str) {
  str = String(str);
  return forbiddenRe.test(str) 
    ? str.replace(forbiddenRe, (c) => forbiddenChars[c])
    : str;
}
ready

Revisions

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