Лучшее решение:
function startsWith(str, word) {
return str.lastIndexOf(word, 0) === 0;
}
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
А вот заканчивается , если вам это тоже нужно:
function endsWith(str, word) {
return str.indexOf(word, str.length - word.length) !== -1;
}
Для тех, кто предпочитает создавать прототип в 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;
});
Использование:
"abc".startsWith("ab")
true
"c".ensdWith("c")
true