The startsWith() method determines whether a string begins with the characters of another string, returning true or false as appropriate.
str.startsWith(searchString[, position])
searchStringpositionsearchString; defaults to 0.This method lets you determine whether or not a string begins with another string.
startsWith()var str = 'To be, or not to be, that is the question.';
console.log(str.startsWith('To be')); // true
console.log(str.startsWith('not to be')); // false
console.log(str.startsWith('not to be', 10)); // true
This method has been added to the ECMAScript 6 specification and may not be available in all JavaScript implementations yet. However, you can polyfill str.startsWith() with the following snippet:
if (!str.startsWith) {
str.startsWith = function(searchString, position) {
position = position || 0;
return this.indexOf(searchString, position) === position;
};
}
A more robust and optimized Polyfill is available str.startsWith">on GitHub by Mathias Bynens.
Created by Mozilla Contributors, license: CC-BY-SA 2.5