• 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

  • 相关阅读:
    Hadoop 2.5.1集群安装配置
    Hadoop 2.5.1编译
    CloudStack安装
    Swift安装
    频率分布折线图与总体密度曲线
    频率直方图(hist)
    分位数(quantile)
    茎叶图(stem)
    盒图(boxplot)
    R语言学习
  • 原文地址:https://www.cnblogs.com/1175429393wljblog/p/8417224.html
Copyright © 2020-2023  润新知