Another alternative with .lastIndexOf:
// does the haystack start with the needle?
haystack.lastIndexOf(needle,0) === 0
This looks backwards through haystack for an occurrence of needle starting from index zero. In other words, it only checks if haystack starts with needle.
lastIndexOf provides a second optional parameter 'fromIndex'. If given, the backwards search starts at this given index position and traverses back to index zero.
When the second parameter is zero, there are only two possible return values of lastIndexOf -- it either returns 0 (success, the haystack does start with the needle) or -1 (the haystack does not start with the needle).
In principle, this should have performance advantages over some other approaches:
- It doesn't search the entire
haystack.
- It doesn't create a new temporary string and then immediately discard it.
The "simpler"
haystack.lastIndexOf(needle) === 0 // incorrect!
may seem to give the correct "startsWith" results in some cases.
This "simpler" version gives incorrect results if there are two copies of the needle in the string -- then lastIndexOf returns the position of the last copy of that needle, which will be greater than zero, and so will always return False, whether or not the string actually does startWith the needle.