regex vs endswith

Benchmark created by lbolla on


Description

Is it faster regex or indexOf, to find if a string ends with a suffix?

Preparation HTML

<script>
  function endswith_indexof(str, suffix) {
      return str.indexOf(suffix, str.length - suffix.length) !== -1;
  }
  function endswith_re(str, suffix) {
      return RegExp(str + '$').test(suffix);
  }
  
  var str = 'this is a string';
  var suffix = 'tring';
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
indexof
endswith_indexof(str, suffix);
ready
regex
endswith_re(str, suffix);
ready

Revisions

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