Add startsWith in IE 11

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

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

Answers


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

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

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().


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

I've been using this polyfill:

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

You can use this. It works with 'Internet Explorer 11' and most of latest browsers. One advantage of this code is if default 'startsWith' and 'endsWith' work with your latest browser then those functions do the job.

function startsWith(str, prefix) {
	if (str.length < prefix.length){ 
		return false;
	}	
	if(String.prototype.startsWith) {
		return str.startsWith(prefix);
	}	
	//return str.slice(0, prefix.length) == prefix;
	return str.substring(0, prefix.length) === prefix;	
}
 
function endsWith(str, suffix) {
	if (str.length < suffix.length){
		return false;
	}	
	if(String.prototype.endsWith) {
		return str.endsWith(suffix);
	}
	return str.substring(str.length - suffix.length, str.length) === suffix;	
}    

/* usage */
var myHtml = "<strong>This is html content</strong>";
var myString = "This is simlpe text for test";

if(startsWith(myHtml, "<strong>")){
	console.log("start with <strong>"); 
}
if(startsWith(myString, 'This')){
	console.log("start with 'This'"); 
}

if(endsWith(myHtml, "</strong>")){
	console.log("ends with </strong>"); 
}

if(endsWith(myString, 'test')){
	console.log("ends with 'test'"); 
}

Need Your Help

Unable to find hprof-conv when launching Android Device Monitor

android android-studio

I am using the Android Studio IDE and the SDK that comes with it.

Why XML file is not rendered properly in Firefox?

xml firefox

I am using Firefox to read XML files, but it is not rendering the XML file properly. What could be the problem? I’m posting the XML sample below: