How would I write the equivalent of C#\'s String.StartsWith in JavaScript?
var haystack = \'hello world\';
var needle = \'he\';
haystack.startsWith(needle)
Since this is so popular I think it is worth pointing out that there is an implementation for this method in ECMA 6 and in preparation for that one should use the 'official' polyfill in order to prevent future problems and tears.
Luckily the experts at Mozilla provide us with one:
https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith
if (!String.prototype.startsWith) {
String.prototype.startsWith = function(searchString, position) {
position = position || 0;
return this.indexOf(searchString, position) === position;
};
}
Please note that this has the advantage of getting gracefully ignored on transition to ECMA 6.