endsWith issue in IE11

I have the below code it’s throwing error some in IE11 “Obect property or method not exist…etc”
After search found the following one in MSDN “String.prototype.EndsWith” polyfill. but I have no idea how to implement that with the below code. Can anyone help me how to implement the prototype with the below code to work in ie.

I should use ‘endsWith’ please dont provide alternatives like match string…:).

myVar = //image URL
if(myVar.endsWith("-img1.png")){
	alert("yeah");
	}else
	{ 
	alert("no luck");
	}

Just add the polyfill above your existing code.

//https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith
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;
  };
}

myVar = //image URL
if(myVar.endsWith("-img1.png")){
  alert("yeah");
} else { 
  alert("no luck");
}

@James_Hibbard: Yeah it’s working instead of this polyfill I have used match case like below, hope I can use the below.

if(myVar.match(“-img1.png$”))

Glad you got it working, but:

??

yeah Pullo good catch… :slight_smile: earlier the code control was not in my hand so asked ‘dont provide alternatives’ now had taken the control ‘used match case’.

you should use endsWith with the polyfill - then when IE dies you can delete the polyfill rather than having to rewrite the code to use the correct method.

@felgall: yes, we can but somehow to avoid polyfill used the match case.

never avoid polyfills - they allow you to use modern code and simply delete the polyfill when no longer required.

the alternative is to use antiquated slower running code and update it massively instead of simply deleting a polyfill.

@felgall: Yes you are right just now I am knowing about polyfills how important those are, thanks for guidance.

A polyfill provides backwards support for older browsers that don’t support a new command - the newer browsers simply run the native command while the polyfill provides an equivalent but slower functionality for old browsers. The alternative is to provide the old slower code to all browsers.

IE11 will never be brought up to date because Microsoft are no longer adding new features to it - it will just get security patches between now and when Microsoft abandon Internet Explorer completely. Their new replacement browser Microsoft Edge was introduced just over a year ago.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.