JavaScript startsWith and endsWith Implementation for Strings
JavaScript is missing the sometimes useful startsWith and endsWith functions that are available in Python, C#, etc. One can argue that startsWith is not necessary since its just as easy to check the index of the prefix and compare to 0:
function strStartsWith(str, prefix) {
return str.indexOf(prefix) === 0;
}
Using indexOf to implement endsWith is possible as well but not as cool and short as using regular expressions:
function strEndsWith(str, suffix) {
return str.match(suffix+"$")==suffix;
}
If you are a fan of monkey-patching JavaScript's builtin classes:
String.prototype.startsWith = function(prefix) {
return this.indexOf(prefix) === 0;
}
String.prototype.endsWith = function(suffix) {
return this.match(suffix+"$") == suffix;
};
Then you can do:
>>> "rickyrosario.com".startsWith("ricky")
true
>>> "rickyrosario.com".endsWith(".com")
true
blog comments powered by Disqus