JavaScript endsWith not working in IEv10?

I am trying to compare two lines in JavaScript using endsWith (), for example

var isValid = string1.endsWith(string2); 

It works great on Google Chrome and Mozilla. When it arrives in IE, it throws a console error as follows

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

How can I solve it?

+13
javascript jquery prototypejs internet-explorer
source share
4 answers

The endsWith() method is not supported in IE. Check browser compatibility here .

You can use the polyfill option taken from the 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; }; } 
+18
source share

I found the simplest answer,

All you need to do is define a prototype

  if (!String.prototype.endsWith) { String.prototype.endsWith = function(suffix) { return this.indexOf(suffix, this.length - suffix.length) !== -1; }; } 
+12
source share

As a rule, it’s a bad practice to extend the prototype of your own JavaScript object. See Here - Why extending native objects to bad practice?

You can use a simple check that will work in a cross browser:

 var isValid = (string1.lastIndexOf(string2) == (string1.length - string2.length)) 
+2
source share

Response to an old question: Developing an alternative for endsWith() in IE11.

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

 var isValid = (string1.lastIndexOf(string2) == (string1.length - string2.length) && string1.lastIndexOf(string2) >= 0); 
0
source share

All Articles