js中startWith、endWith 函數不能在任何瀏覽器兼容的問題


在做js測試的時候用到了startsWith函數,但是他並不是每個瀏覽器都有的,所以我們一般要重寫一下這個函數,具體的用法可以稍微總結一下

在有些瀏覽器中他是undefined 所以我們可以這樣的處理一下、

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



這個需要放在頁面剛要加載完成的函數里,不然不好使。

 

還有一種直接重寫 不過我沒測試過,你們可以測試一下:

  1. String.prototype.startWith=function(str){    
  2.   if(str==null||str==""||this.length==0||str.length>this.length)    
  3.    return false;    
  4.   if(this.substr(0,str.length)==str)    
  5.      return true;    
  6.   else    
  7.      return false;    
  8.   return true;    
  9. }    


有的說js中沒有startsWith 和endWith這兩個函數不過就算不聲明有些瀏覽器他還是可以用的,不過為了兼容性還是希望重寫一下。

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


采用正則表達式實現startWith、endWith效果函數

 
  1. String.prototype.startWith=function(str){  
  2. var reg=new RegExp("^"+str);  
  3. return reg.test(this);  
  4. }  
  5. //測試ok,直接使用str.endWith("abc")方式調用即可  
  6. String.prototype.endWith=function(str){  
  7. var reg=new RegExp(str+"$");  
  8. return reg.test(this);  

原文鏈接:http://blog.csdn.net/q1059081877q/article/details/49912583


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM