Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS: In IE11, string method endsWith() is not working

When I tried this.form.name.endsWith("$END$") in IE11, getting following error.

Object doesn't support property or method 'endsWith'

In Chrome, its working fine. Is there any alternative string method in IE11

like image 366
cpp_learner Avatar asked Apr 17 '18 06:04

cpp_learner


2 Answers

You may use the polyfill instead

if (!String.prototype.endsWith) {
    String.prototype.endsWith = function(search, this_len) {
        if (this_len === undefined || this_len > this.length) {
            this_len = this.length;
        }
        return this.substring(this_len - search.length, this_len) === search;
    };
}

Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith

like image 162
Mohhamad Hasham Avatar answered Oct 02 '22 08:10

Mohhamad Hasham


In IE11 there is no endsWith implemented. You will have to use a polyfill like the one from mdn

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 23
Joschi Avatar answered Oct 02 '22 06:10

Joschi