You can add this function to the String prototype
:
if(typeofString.prototype.startsWith !=\'function\'){// see below for better implementation!String.prototype.startsWith =function(str){returnthis.indexOf(str)===0;};}
Then you can use it directly on string values:
\"Hello World!\".startsWith(\"He\");// truevar data =\"Hello world\";var input =\'He\';
data.startsWith(input);// true
Edit: Note that I\'m checking if the function exists before defining it, that\'s because in the future, the language might have this strings extras methods defined as built-in functions, and native implementations are always faster and preferred, see the ECMAScript Harmony String Extras proposal.
Edit: As others noted, indexOf
will be inefficient for large strings, its complexity is O(N)
. For a constant-time solution (O(1)
), you can use either, substring
as @cobbal suggested, or String.prototype.slice
, which behaves similarly (note that I don\'t recommend using the substr
, because it\'s inconsistent between implementations (most notably on JScript) ):
if(typeofString.prototype.startsWith !=\'function\'){String.prototype.startsWith =function(str){returnthis.slice(0, str.length)== str;};}
The difference between substring
and slice
is basically that slice
can take negative indexes, to manipulate characters from the end of the string, for example you could write the counterpart endsWith
method by:
if(typeofString.prototype.endsWith !=\'function\'){String.prototype.endsWith =function(str){returnthis.slice(-str.length)== str;};}