cpp_learner
cpp_learner

Reputation: 382

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

Upvotes: 6

Views: 10821

Answers (4)

Mohhamad Hasham
Mohhamad Hasham

Reputation: 2032

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

Upvotes: 8

Gregory Bologna
Gregory Bologna

Reputation: 285

I prefer a shim cdn as I don't need to worry about another developer breaking the js. For Wordpress, use this.

wp_enqueue_script( 'polyfill', 'https://cdn.polyfill.io/v2/polyfill.min.js' , false, '2.0.0', true);

Upvotes: 0

phihag
phihag

Reputation: 288190

As laid out here and on MDN, IE11 does not support String.endsWith. You can either use a polyfill - which adds support for endsWith onto the String object - or use existing JavaScript functions, for instance String.match or RegExp.test:

this.form.name.match(/\$END\$$\)

Upvotes: 1

Joschi
Joschi

Reputation: 2974

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;
  };
}

Upvotes: 2

Related Questions