Javascript中实现String.startsWith和endsWith方法
在操作字符串(String)类型的时候,startsWith(anotherString)和endsWith(anotherString)是非常好用的方法。其中startsWith判断当前字符串是否以anotherString作为开头,而endsWith则是判断是否作为结尾。举例:
"abcd".startsWith("ab");//true
"abcd".startsWith("bc");//false
"abcd".endsWith("cd");//true
"abcd".endsWith("e");//false
"a".startsWith("a");//true
"a".endsWith("a");//true
但不幸的是,Javascript中没有自带这两个方法,需要的话只能自己写。当然写起来也不难就是了。
if(typeofString.prototype.startsWith!='function'){
String.prototype.startsWith=function(prefix){
returnthis.slice(0,prefix.length)===prefix;
};
}
String.slice()和String.substring()类似,都是获得一段子串,但有评测说slice的效率更高。这里不使用indexOf()的原因是,indexOf会扫描整个字符串,如果字符串很长,indexOf的效率就会很差。
if(typeofString.prototype.endsWith!='function'){
String.prototype.endsWith=function(suffix){
returnthis.indexOf(suffix,this.length-suffix.length)!==-1;
};
}
和startsWith不一样,endsWith中可以使用indexOf。原因是它只扫描了最后的一段字符串,而比起slice的优势是它不用复制字符串,直接扫描即可,所以效率更高。
热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下