浅谈js中startsWith 函数不能在任何浏览器兼容的问题
作者:jingxian 时间:2024-04-23 09:11:38
在做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);
}
标签:js,startswith,函数,浏览器,兼容
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Python实现自动化发送邮件
2023-12-07 14:39:58
![](https://img.aspxhome.com/file/2023/7/67827_0s.jpg)
keras 特征图可视化实例(中间层)
2021-12-05 22:54:46
![](https://img.aspxhome.com/file/2023/4/117924_0s.jpg)
processlist命令 查看mysql 线程
2024-01-24 02:58:30
JavaScript 自动分号插入(JavaScript synat:auto semicolon insertion)
2013-08-09 10:14:56
python爬取豆瓣电影TOP250数据
2021-12-27 12:50:17
![](https://img.aspxhome.com/file/2023/9/95199_0s.png)
Python趣味挑战之实现简易版音乐播放器
2021-06-25 15:13:43
![](https://img.aspxhome.com/file/2023/7/67867_0s.png)
python解析发往本机的数据包示例 (解析数据包)
2021-05-24 13:42:49
python 根据网易云歌曲的ID 直接下载歌曲的实例
2021-01-15 19:48:47
![](https://img.aspxhome.com/file/2023/5/101205_0s.jpg)
Django如何实现网站注册用户邮箱验证功能
2023-05-14 08:03:08
![](https://img.aspxhome.com/file/2023/9/94049_0s.png)
Python的Django框架中的数据过滤功能
2022-02-01 05:48:40
python使用reportlab画图示例(含中文汉字)
2022-10-22 17:14:18
python使用html2text库实现从HTML转markdown的方法详解
2023-07-18 09:00:03
js实现类bootstrap模态框动画
2024-04-18 09:31:12
js运动动画的八个知识点
2024-06-07 15:27:25
MySQL获取binlog的开始时间和结束时间(最新方法)
2024-01-23 12:13:31
![](https://img.aspxhome.com/file/2023/2/84542_0s.png)
HTML 5 预览
2008-01-24 12:17:00
![](https://img.aspxhome.com/file/UploadPic/20081/24/2008124122637981s.gif)
Python导入Excel表格数据并以字典dict格式保存的操作方法
2023-05-25 17:58:37
![](https://img.aspxhome.com/file/2023/8/104868_0s.png)
ASP中使用存储过程介绍
2008-10-10 12:10:00
微信小程序使用uni-app一键获取用户信息
2024-05-05 09:07:09
![](https://img.aspxhome.com/file/2023/1/130851_0s.png)
jQuery+AJAX实现网页无刷新上传
2024-04-17 10:39:39
![](https://img.aspxhome.com/file/2023/8/136188_0s.jpg)