How would I write the equivalent of C#\'s String.StartsWith in JavaScript?
var haystack = \'hello world\';
var needle = \'he\';
haystack.startsWith(needle)
Best solution:
function startsWith(str, word) {
return str.lastIndexOf(word, 0) === 0;
}
And here is endsWith if you need that too:
function endsWith(str, word) {
return str.indexOf(word, str.length - word.length) !== -1;
}
For those that prefer to prototype it into String:
String.prototype.startsWith || (String.prototype.startsWith = function(word) {
return this.lastIndexOf(word, 0) === 0;
});
String.prototype.endsWith || (String.prototype.endsWith = function(word) {
return this.indexOf(word, this.length - word.length) !== -1;
});
Usage:
"abc".startsWith("ab")
true
"c".ensdWith("c")
true
With method:
startsWith("aaa", "a")
true
startsWith("aaa", "ab")
false
startsWith("abc", "abc")
true
startsWith("abc", "c")
false
startsWith("abc", "a")
true
startsWith("abc", "ba")
false
startsWith("abc", "ab")
true