<script type="text/javascript">
var str = "我中间a有个字母A";
/*
1给索引差字符charAt/charCodeAt
参数:字符索引位置
返回值:索引对应的字符,若参数不在0-str.length,改方法会返回一个空字符串、NaN
*/
console.log(str.charAt(3))//a 返回字符串
console.log(str.charAt(100))//空字符串
console.log(str.charCodeAt(3))//97 返回ASCII码
console.log(str.charCodeAt(100))//NaN
/*
2给字符,查索引indexOf、lastIndexOf;
参数:需要查找的字符
返回值:该字符的索引值,
indexOf 查找的是你需要查找的字符在字符串中第一次出现
lastIndexOf查找的你需要查找的字符在字符串中最后一次出现
如果没有找到字符,返回值为-1
*/
console.log("-----------------------------")
console.log(str.indexOf("a"));//3
console.log(str.lastIndexOf("我"));//0
console.log(str.indexOf("?"));//-1
console.log(str.lastIndexOf("?"));//-1
/*
字符串截取:string.slice(star,end)
参数:从索引为star开始截取到end索引的字符串;
注意:截取包括star但不包括end(包头不包尾)
若star>end,获取不到值
如均为负数,表示从后往前数,索引值从-1开始
*/
console.log("-----------------------------")
console.log(str.slice(0))//我中间a有个字母A
console.log(str.slice(3,4));//a
console.log(str.slice(-1,-3));//因为-1<-3所以不能打印值\
/*
字符串截取:string.substr(star,count)
参数:从索引为star开始截取count个字符串;
注意:截取包括star但不包括end(包头不包尾)
若star>end时,计算机智能调序从前往后排
如均为负数,表示从后往前数,索引值从-1开始
*/
console.log("-----------------------------")
console.log(str.substr(3,4));//a有个字
console.log(str.substr(5,5));//个字母A
console.log(str.substr(-1,-4));//打印不出来
// console.log(str.substr(-1);//报错
</script>
通过字符串找字符索引,通过字符找字符索引值,截取字符串
最新推荐文章于 2022-05-27 07:41:46 发布