30

IE 11 does not support startsWith with strings. (Look here)

How do you add a prototype so that it supports the method?

1
  • 2
    For future reference and to hopefully help future searches: The error that appears in IE is: TypeError: Object doesn't support property or method 'startsWith' Commented Nov 19, 2016 at 23:57

5 Answers 5

71

Straight from the MDN page, here's the polyfill:

if (!String.prototype.startsWith) {
    Object.defineProperty(String.prototype, 'startsWith', {
        value: function(search, rawPos) {
            var pos = rawPos > 0 ? rawPos|0 : 0;
            return this.substring(pos, pos + search.length) === search;
        }
    });
}

This is safe to use in any browser. If the method already exists, this code will see that and do nothing. If the method does not exist, it will add it to the String prototype so it is available on all strings.

You just add this to one of your JS files in some place where it executes at startup and before you attempt to use .startsWith().

If you want a polyfill version that follows the specification in its entirety, including all possible error checks, you can get that here, but you will probably have to use that with a bundler in the browser because of the way the polyfill is spread out among several files.

9
  • Do you just add it straight to the JS file? Commented Mar 25, 2016 at 3:17
  • people should def look there they usually always have a nice polyfill
    – EasyBB
    Commented Mar 25, 2016 at 3:17
  • 1
    @SandahAung yes before you want to use it
    – EasyBB
    Commented Mar 25, 2016 at 3:18
  • substr() function is considered a legacy function according to mozilla developer: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…. If possible, use the substring() method instead (Recommended by MDN).
    – fatih
    Commented May 24, 2020 at 10:06
  • @fatih - MDN has apparently updated their polyfill to use .substring() so I edited the answer to reflect that.
    – jfriend00
    Commented May 24, 2020 at 15:06
15

Found an easier way to fix this,

function startsWith(str, word) {
    return str.lastIndexOf(word, 0) === 0;
}

like wise to find the endswith use below code,

function endsWith(str, word) {
    return str.indexOf(word, str.length - word.length) !== -1;
}

Links to browser support.

5
  • 1
    Need to check first if the function exists or not?
    – Richard
    Commented Jan 4, 2021 at 14:58
  • IndexOf functions are there, I have tested this.
    – tk_
    Commented Jan 5, 2021 at 7:33
  • Sure, but you don't want to use the polyfill if the browser supports the functionality natively? Don't mean testing for indexOf, but endsWith
    – Richard
    Commented Jan 5, 2021 at 9:03
  • I'm not sure there is. However, in 2017 there was no. if you added it now it will just get overridden by this.
    – tk_
    Commented Jan 5, 2021 at 10:18
  • 1
    Yeah it's very much supported by modern browsers :-)
    – Richard
    Commented Jan 5, 2021 at 14:20
3

I've been using this polyfill:

if (typeof String.prototype.startsWith != 'function') {
    String.prototype.startsWith = function(prefix) {
        return this.slice(0, prefix.length) == prefix;
    };
}
3
  • FWIW, this polyfill isn't fully spec compliant. IMO better to simply declare it as a global function so you don't have potentially different behavior depending on whether the polyfill is used (or use a compliant polyfill).
    – snarf
    Commented Aug 20, 2020 at 1:49
  • @snarf can you elaborate or post a link to the full spec? This code could be put in a global function. Commented Aug 21, 2020 at 20:07
  • MDN reference has a link to the specification. And yes, it could be a global function (or better yet a ponyfill), but my point is that it isn't.
    – snarf
    Commented Aug 21, 2020 at 22:58
0

I've reviewed and edited my answer. I believe that my code is now much more appropriate than before.

If your browser supports built-in 'startsWith' function then that built-in function will be use. Additionally I've included 'endsWith' also.

if (typeof String.prototype.startsWith !== 'function') {
   String.prototype.startsWith = function(searchString, position) {	
       position = position || 0;
       return this.substring(position,  position + searchString.length) === searchString;
   }
}


if (typeof String.prototype.endsWith !== 'function') {
   String.prototype.endsWith = function(searchString, strtLength) {	
      strtLength = (strtLength === undefined || strtLength > this.length)? this.length : strtLength;  	
      return this.substring(strtLength - searchString.length, strtLength) === searchString;
   }
}

  

/* usage */

let str = 'To be, or not to be, that is the question.'

console.log(str.startsWith('To be'))          // true
console.log(str.startsWith('not to be'))      // false
console.log(str.startsWith('not to be', 10))  // true

let str2 = 'To be, or not to be, that is the question.'
console.log(str2.endsWith('question.'))  // true
console.log(str2.endsWith('to be'))      // false
console.log(str2.endsWith('to be', 19))  // true

0
if (!String.prototype.endsWith) {
    String.prototype.endsWith = function (text) {
        return this.indexOf(text, this.length - text.length) !== -1;
    };
}

if (!String.prototype.startsWith) {
    String.prototype.startsWith = function (text) {
        return this.lastIndexOf(text, 0) === 0;
    };
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.