在做js測試的時候用到了startsWith函數,但是他並不是每個瀏覽器都有的,所以我們一般要重寫一下這個函數,具體的用法可以稍微總結一下
在有些瀏覽器中他是undefined 所以我們可以這樣的處理一下、
- if (typeof String.prototype.startsWith != 'function') {
- String.prototype.startsWith = function (prefix){
- return this.slice(0, prefix.length) === prefix;
- };
- }
這個需要放在頁面剛要加載完成的函數里,不然不好使。
還有一種直接重寫 不過我沒測試過,你們可以測試一下:
- 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;
- }
有的說js中沒有startsWith 和endWith這兩個函數不過就算不聲明有些瀏覽器他還是可以用的,不過為了兼容性還是希望重寫一下。
- if (typeof String.prototype.endsWith != 'function') {
- String.prototype.endsWith = function(suffix) {
- return this.indexOf(suffix, this.length - suffix.length) !== -1;
- };
- }
采用正則表達式實現startWith、endWith效果函數
- 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);
- }
原文鏈接:http://blog.csdn.net/q1059081877q/article/details/49912583