JavaScript endsWith is not working in IEv10?

Sivaprasad derangula picture Sivaprasad derangula · May 31, 2016 · Viewed 12.6k times · Source

I'm trying to compare two strings in JavaScript using endsWith(), like

var isValid = string1.endsWith(string2);

It's working fine in Google Chrome and Mozilla. When comes to IE it's throwing a console error as follows

SCRIPT438: Object doesn't support property or method 'endsWith' 

How can I resolve it?

Answer

Pranav C Balan picture Pranav C Balan · May 31, 2016

Method endsWith() not supported in IE. Check browser compatibility here.

You can use polyfill option taken from MDN documentation:

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