How would I write the equivalent of C#\'s String.StartsWith in JavaScript?
var haystack = \'hello world\';
var needle = \'he\';
haystack.startsWith(needle)
I recently asked myself the same question.
There are multiple possible solutions, here are 3 valid ones:
s.indexOf(starter) === 0
s.substr(0,starter.length) === starter
s.lastIndexOf(starter, 0) === 0
(added after seeing Mark Byers's answer)using a loop:
function startsWith(s,starter) {
for (var i = 0,cur_c; i < starter.length; i++) {
cur_c = starter[i];
if (s[i] !== starter[i]) {
return false;
}
}
return true;
}
I haven't come across the last solution which makes uses of a loop.
Surprisingly this solution outperforms the first 3 by a significant margin.
Here is the jsperf test I performed to reach this conclusion: http://jsperf.com/startswith2/2
Peace
ps: ecmascript 6 (harmony) introduces a native startsWith
method for strings.
Just think how much time would have been saved if they had thought of including this much needed method in the initial version itself.
Update
As Steve pointed out (the first comment on this answer), the above custom function will throw an error if the given prefix is shorter than the whole string. He has fixed that and added a loop optimization which can be viewed at http://jsperf.com/startswith2/4.
Note that there are 2 loop optimizations which Steve included, the first of the two showed better performance, thus I will post that code below:
function startsWith2(str, prefix) {
if (str.length < prefix.length)
return false;
for (var i = prefix.length - 1; (i >= 0) && (str[i] === prefix[i]); --i)
continue;
return i < 0;
}