17

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?

Sivaprasad derangula
  • 1,169
  • 4
  • 12
  • 29

4 Answers4

22

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;
  };
}
radbyx
  • 9,352
  • 21
  • 84
  • 127
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
  • It helps to know that this script can be placed anywhere. Ideally it is loaded as the page loads too so that it is made available to all other functions – David Brossard Aug 29 '17 at 14:26
  • Find the simplified answer here https://stackoverflow.com/questions/37544376/javascript-endswith-is-not-working-in-iev10#answer-37545037 – Sivaprasad derangula Nov 07 '17 at 05:10
18

I found the simplest answer,

All you need do is to define the prototype

 if (!String.prototype.endsWith) {
   String.prototype.endsWith = function(suffix) {
     return this.indexOf(suffix, this.length - suffix.length) !== -1;
   };
 }
Sivaprasad derangula
  • 1,169
  • 4
  • 12
  • 29
  • Kudos. Anyway, I think `string.indexOf(suffix, string.length - suffix.length) !== -1;` is sufficient, since altering the prototype is a bad idea – Marco Sulla Feb 15 '23 at 10:31
2

It's generally bad practise to extend the prototype of a native JavaScript object. See here - Why is extending native objects a bad practice?

You can use a simple check like this that will work cross-browser:

var isValid = (string1.lastIndexOf(string2) == (string1.length - string2.length))
Community
  • 1
  • 1
Chris Halcrow
  • 28,994
  • 18
  • 176
  • 206
0

Reaction on an old issue: Elaborating on alternative for endsWith() in IE11.

To avoid that string1 = "a", string2 = "bc"; would return true:

var isValid = (string1.lastIndexOf(string2) == (string1.length - string2.length) && string1.lastIndexOf(string2) >= 0);
Guillermo Cacheda
  • 2,162
  • 14
  • 23
HansW
  • 1