Check if string starts with or ends with a given string with JavaScript

In ECMAScript 6 Harmony there will be `startsWith` and `endsWith` methods. Here's how to use those and how to write a polyfill.

Native ES6 methods

Here’s the basics of String.prototype.startsWith() and String.prototype.endsWith():

var str = '#something';

if (str.endsWith('g')) {
  console.log('Ends in g');
}

if (str.startsWith('#')) {
  console.log('The string might be an id');
}

Very simple :)

At the time of writing this, these are only supported in Chrome 41 and FireFox 17. Let’s look some polyfills and functions next.

Functions and polyfills

Use lastIndexOf to check if string start with another string, it’s so short that no wrapping function is necessarely needed:

// The string to check
var str = '#something';

if (str.lastIndexOf('#', 0) === 0) {
    console.log('Looks like str is an id');
} else if (str.lastIndexOf('.', 0) === 0) {
    console.log('Looks like str is a class name');
} else {
    console.log("It's just a string, might be an reference to an element");
}

endsWith is not that much more complicated:

var str = '#something';
if (str.lastIndexOf('g', str.length - 1) === str.length - 1) {
    console.log('Ends in g');
}

Function wrapper

Simplified example:

// Starts with
String.prototype.startsWith = function(suffix) {
    return this.indexOf(suffix, 0) === 0;
};

// End width
String.prototype.endsWith = function(suffix) {
    return this.indexOf(suffix, this.length - suffix.length) !== -1;
};

// Usage:
var str = '#something';
if (str.endsWith('g')) {
  console.log('Ends in g');
}

The ‘official’ polyfill

This is taken from the MDN article, it uses the same underlying technique, but it also takes the position parameter:

if (!String.prototype.startsWith) {
  Object.defineProperty(String.prototype, 'startsWith', {
    enumerable: false,
    configurable: false,
    writable: false,
    value: function(searchString, position) {
      position = position || 0;
      return this.lastIndexOf(searchString, position) === position;
    }
  });
}

And the same for endsWith from the corresponding MDN article:

if (!String.prototype.endsWith) {
  String.prototype.endsWith = function(searchString, position) {
      var subjectString = this.toString();
      if (position === undefined || position > subjectString.length) {
        position = subjectString.length;
      }
      position -= searchString.length;
      var lastIndex = subjectString.indexOf(searchString, position);
      return lastIndex !== -1 && lastIndex === position;
  };
}

Club-Mate, the beverage → club-mate.fi