Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript endsWith is not working in IEv10?

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?

like image 849
Sivaprasad derangula Avatar asked May 31 '16 11:05

Sivaprasad derangula


People also ask

How to use endsWith function in JavaScript?

str. endsWith() function is used to check whether the given string ends with the characters of the specified string or not. Arguments: The first argument to this function is a string of characters searchString which is to be searched at the end of the given string.

What is endsWith in JavaScript?

The endsWith() method returns true if a string ends with a specified string. Otherwise it returns false . The endsWith() method is case sensitive.

What do you mean by endsWith () function?

The endswith() method returns True if the string ends with the specified value, otherwise False.


2 Answers

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;
  };
}
like image 80
Pranav C Balan Avatar answered Sep 28 '22 16:09

Pranav C Balan


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;
   };
 }
like image 42
Sivaprasad derangula Avatar answered Sep 28 '22 18:09

Sivaprasad derangula