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