本篇简单地列举了prototype的几个String下检索的api:
1、include(substring)
------判断字符串是否还有指定的参数字符串。返回的是Boolean。
/*
@example
'Zhangyaochun'.include('an'); //true
*/
源码:
/*
其实就是原生的indexOf看一下
*/
include:function(str){
return this.indexOf(str) > -1;
}
2、startsWith(substring)
-------判断字符串是否已指定的参数字符串开始。返回的是Boolean。
/*
@example
'zhangYaochun'.startsWith('z'); //true
'zhangYaochun'.startsWith('Z'); //false
*/
源码:
/*
@还是原生的indexOf
*/
startsWith:function(str){
return this.indexOf(str) === 0;
}
3、endsWith(substring)
-------判断字符串是否已指定的参数字符串结束。返回的是Boolean。
/*
@example
'zhangyaochun'.endsWith('n'); //true
'zhangyaochun'.endsWith('a'); //false
*/
源码:
/*
有依赖于lastIndexOf
*/
endsWith:function(str){
//判断一下参数str的长度是否大于本身的长度
var d = this.length - str.length;
d >= 0 && this.lastIndexOf(str) === d;
}

本文介绍了JavaScript中String原型下的三个实用API:includes用于检查字符串是否包含子串;startsWith用于判断字符串是否以特定子串开头;endsWith则用于确认字符串是否以特定子串结尾。这些方法简化了字符串操作流程。
1466

被折叠的 条评论
为什么被折叠?



