Thursday, July 21, 2016

JavaScript Equivalents of StartsWith and EndsWith

As a .NET developer I sometimes find myself knowing how to do something in C#, but not being able to do the same thing in JavaScript (or some other language).  Usually a quick Google search will turn up a nice equivalent of a built-in function, but sometimes it's not so easy.  I recently needed the equivalents of C#'s StartsWith and EndsWith, which check whether a string starts or ends with another string, respectively.  It turns out JavaScript has pretty easy ways to do both using the substr function.

EndsWith:
statement.substr( -1 * (searchString.length) ) === searchString;

StartsWith:
statement.substr(0, searchString.length) === searchString;

I could add those to the string.prototype in JavaScript and then reference them the same was I do in C#, too.  Like this:
String.prototype.startsWith = function(searchString) {
  return this.substr(0, searchString.length) === searchString;
};

String.prototype.endsWith = function(searchString) {
  return this.substr(-1 * (searchString.length)) === searchString;
};

statement.startsWith(searchString);
statement.endsWith(searchString);

Neat, huh?!