Talking about the problem that startsWith function in js can not be compatible with any browser

  • 2021-07-26 06:03:42
  • OfStack

When doing js test, we use startsWith function, but it is not available in every browser, so we need to rewrite this function, and the specific usage can be summarized slightly.

In some browsers, it is undefined, so we can handle it like this.


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

This needs to be placed in the function that the page is just about to load, otherwise it will not work well.

There is another direct rewrite, but I haven't tested it. You can test it 1 time:


String.prototype.startWith=function(str){ 
 if(str==null||str==""||this.length==0||str.length>this.length) 
  return false; 
 if(this.substr(0,str.length)==str) 
   return true; 
 else 
   return false; 
 return true; 
} 

Some say that there are no startsWith and endWith functions in js, but even if some browsers are not declared, they can still be used, but for compatibility, they still want to rewrite 1.


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

Realization of startWith and endWith effect functions by regular expressions


String.prototype.startWith=function(str){
var reg=new RegExp("^"+str);
return reg.test(this);
}
// Test ok , direct use str.endWith("abc") You can call it in a way 
String.prototype.endWith=function(str){
var reg=new RegExp(str+"$");
return reg.test(this);
} 


Related articles: