How would I write the equivalent of C#\'s String.StartsWith in JavaScript?
var haystack = \'hello world\';
var needle = \'he\';
haystack.startsWith(needle)
You can also return all members of an array that start with a string by creating your own prototype / extension to the the array prototype, aka
Array.prototype.mySearch = function (target) {
if (typeof String.prototype.startsWith != 'function') {
String.prototype.startsWith = function (str){
return this.slice(0, str.length) == str;
};
}
var retValues = [];
for (var i = 0; i < this.length; i++) {
if (this[i].startsWith(target)) { retValues.push(this[i]); }
}
return retValues;
};
And to use it:
var myArray = ['Hello', 'Helium', 'Hideout', 'Hamster'];
var myResult = myArray.mySearch('Hel');
// result -> Hello, Helium