Add startsWith in IE 11

Viewed 31750

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

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

5 Answers

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.

I've been using this polyfill:

if (typeof String.prototype.startsWith != 'function') {
    String.prototype.startsWith = function(prefix) {
        return this.slice(0, prefix.length) == prefix;
    };
}

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

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