Home > Web Front-end > JS Tutorial > The startsWith function in js is not compatible with any browser

The startsWith function in js is not compatible with any browser

高洛峰
Release: 2017-03-01 15:38:15
Original
1816 people have browsed it

The startsWith function is used when doing js testing, but it is not available in every browser, so we generally need to rewrite this function. The specific usage can be briefly summarized

In some browsers it is undefined, so we can deal with it like this,

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

This needs to be placed in the function just after the page is loaded. Otherwise it won't work.

There is also a direct rewrite but I have not tested it. You can test it:

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; 
}
Copy after login

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

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

Use regular expressions to implement startWith and endWith effect functions

String.prototype.startWith=function(str){
var reg=new RegExp("^"+str);
return reg.test(this);
}
//测试ok,直接使用str.endWith("abc")方式调用即可
String.prototype.endWith=function(str){
var reg=new RegExp(str+"$");
return reg.test(this);
}
Copy after login

The above The problem that the startsWith function in js is not compatible with any browser is all the content shared by the editor. I hope it can give you a reference, and I also hope that everyone will support the PHP Chinese website.

For more related articles on the issue that the startsWith function in js is not compatible with any browser, please pay attention to the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template