regex replace

Benchmark created on


Setup



const ESCAPED_REGEX = /[<"'&]/
const a =/&/g
const b = /</g
const c = /"/g
const d = /'/g

function s1(str) {
   return str.replace(a, '&amp;').replace(b, '&lt;').replace(c, '&#34;').replace(d, '&#39;');
  }
  
  function s2(value) {
    // This is a optimization to avoid the whole escaping process when the value
  // does not contain any special characters.
  if (!ESCAPED_REGEX.test(value)) {
    return value
  }

  const length = value.length
  let escaped = ''

  let start = 0
  let end = 0

  for (; end < length; end++) {
    // https://wonko.com/post/html-escaping
    switch (value[end]) {
      case '&':
        escaped += value.slice(start, end) + '&amp;'
        start = end + 1
        continue
      // We don't need to escape > because it is only used to close tags.
      // https://stackoverflow.com/a/9189067
      case '<':
        escaped += value.slice(start, end) + '&lt;'
        start = end + 1
        continue
      case '"':
        escaped += value.slice(start, end) + '&#34;'
        start = end + 1
        continue
      case "'":
        escaped += value.slice(start, end) + '&#39;'
        start = end + 1
        continue
    }
  }

  // Appends the remaining string.
  escaped += value.slice(start, end)

  return escaped
  }
  
  function s3(value) {
   

  const length = value.length
  let escaped = ''

  let start = 0
  let end = 0

  for (; end < length; end++) {
    // https://wonko.com/post/html-escaping
    switch (value[end]) {
      case '&':
        escaped += value.slice(start, end) + '&amp;'
        start = end + 1
        continue
      // We don't need to escape > because it is only used to close tags.
      // https://stackoverflow.com/a/9189067
      case '<':
        escaped += value.slice(start, end) + '&lt;'
        start = end + 1
        continue
      case '"':
        escaped += value.slice(start, end) + '&#34;'
        start = end + 1
        continue
      case "'":
        escaped += value.slice(start, end) + '&#39;'
        start = end + 1
        continue
    }
  }

  // Appends the remaining string.
  escaped += value.slice(start, end)

  return escaped
  }

Test runner

Ready to run.

Testing in
TestOps/sec
s1
s1('if (a < \'\'b && c > d) {""} // Héllö naõ')
ready
s2
s2('if (a < \'\'b && c > d) {""} // Héllö naõ')
ready
s3
s3('if (a < \'\'b && c > d) {""} // Héllö naõ')
ready

Revisions

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