Jul 01

JavaScript startsWith and endsWith Implementation for Strings

An implementation of endsWith and startsWith functions for strings in JavaScript

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

Tags:

Powered by my hackings on Django-Mingus a Django project, PostgreSQL, memcached, nginx, Apache + mod_wsgi, Ubuntu, Rackspace Cloud,...

Disclaimer: The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

html5 | top