JS startsWith

JavaScript performance comparison

Revision 5 of this test case created by timmywil

Info

// Unfortunately, this doesn't work for checking if a string starts with a prefix e.g. 'hehe'.lastIndexOf('he') === 0 // false

// Any of these other options will work

Preparation code

<script>
  // sample data
  var origString = 'hello, world',
      testString = 'he';
</script>

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
indexOf
origString.indexOf(testString) === 0;
pending…
create regex, then test
var r = new RegExp('^' + testString);
r.test(origString);
pending…
lastIndexOf
origString.lastIndexOf(testString) === 0;
pending…
substring
origString.substring(0, testString.length) === testString;
pending…
substr
origString.substr(0, testString.length) === testString;
pending…

Compare results of other browsers

Revisions

You can edit these tests or add even more tests to this page by appending /edit to the URL. Here’s a list of current revisions for this page:

0 comments

Add a comment