Creating JavaScript string startsWith() and endsWith() functions

By Steve Claridge on 2014-03-15.

JavaScript strings don't have native startsWith() or endsWith() functions. Fortunately it is very easy to add them to the string prototype so that you can use them throughout your code. Here's some code for the two functions:

if ( typeof String.prototype.startsWith != 'function' ) {
  String.prototype.startsWith = function( str ) {
    return this.substring( 0, str.length ) === str;
  }
}; alert( "hello world".startsWith( "hello" ) ); if ( typeof String.prototype.endsWith != 'function' ) {
  String.prototype.endsWith = function( str ) {
    return this.substring( this.length - str.length, this.length ) === str;
  }
}; alert( "hello world".endsWith( "world" ) );

It is worth noting that the functions above will return true if "" is passed as the string to compare, these will return true

"hello world".startsWith( "" );
"hello world".endsWith( "" );

If you don't want this to happen then add a length check to the two functions, so they now look like this:

if ( typeof String.prototype.startsWith != 'function' ) {
  String.prototype.startsWith = function( str ) {
    return str.length > 0 && this.substring( 0, str.length ) === str;
  }
}; if ( typeof String.prototype.endsWith != 'function' ) {
  String.prototype.endsWith = function( str ) {
    return str.length > 0 && this.substring( this.length - str.length, this.length ) === str;
  }
};

In the code above I'm using substring() to check if a string starts or ends with the parameter, this is quicker than usingindexOf() as that has to scan the whole string to find a match and that can be slow for long strings.