How would I write the equivalent of C#\'s String.StartsWith in JavaScript?
var haystack = \'hello world\';
var needle = \'he\';
haystack.startsWith(needle)
Another alternative with .lastIndexOf:
haystack.lastIndexOf(needle, 0) === 0
This looks backwards through haystack
for an occurrence of needle
starting from index 0
of haystack
. In other words, it only checks if haystack
starts with needle
.
In principle, this should have performance advantages over some other approaches:
haystack
.