实例:var str = "Hello World";
IE7及以前更早的浏览器不支持str[1](中括号取数组中某个字符),那么就可以使用charAt(索引)和charCodeAt()函数
String中获取的方法
charAt()函数使用
charAt(索引号),索引在有效范围内返回具体字符。


否则返回空:


charCodeAt()函数使用
当索引有效时,返回的是该字符的编码:


当超过字符串的索引范围时,返回NaN(not a number):


indexOf()函数使用
从左侧开始,检测字符在字符串中的索引值:
使用:str.indexOf("o")
返回值:(1)字符出现在字符串中:返回第一次出现的索引值。(2)字符没有出现在字符串中:返回-1




lastIndexOf()函数使用
从右侧开始,检测字符在字符串中的索引值:
使用:str.lastIndexOf("o")
返回值:(1)字符出现在字符串中:返回第一次出现的索引值。(2)字符没有出现在字符串中:返回-1


String中截取的方法
slice()方法
使用:str.slice(start, [end]) 其中start为起始索引(包含),end为结束索引(不包含),其中end为可选参数,没有end,则截取到字符串末尾。


当start和end为负数时,slice()方法会使用字符串长度加上负数。


substring()方法
使用:str.substring(start, [end]),和slice()函数的用法一样,但是当参数为负数的时候,会自动转换为0,并且会重新调整两个参数大小顺序。


当两个参数都是负数的时候:


substr()方法
使用:str.substr(start,[len]),第一个参数为起始索引位置,第二个参数为截取的字符串长度。遇到负数,和slice处理方法一样(字符串长度加上负数)。


综合实训
编写一个JS函数,用于获取输入参数的后缀名,如输入abc.txt,返回.txt


split()方法
使用:str.split(separator),将字符串转换为字符数组,其中用separator进行分割:


replace()方法
使用:str.replace(substring, replacement) ,两个参数都必须,只替换第一次出现的substring,只替换一次。


综合实训
将 使用 "-" 连接的字符串转换为驼峰命名方式:


网友评论