截取字符串的长度
1、substring(3,6) 从索引3的位置开始截取,截取6个长度,也就是截取到索引是9的位置
2、substr(3,6) 从索引3的位置 截取到索引6的位置。
charAt()
该方法可返回指定位置的字符。返回的字符是长度为 1 的字符串。
语法:stringObject.charAt(index)
-
index:必填,所要提取字符的位置 var mystr="I love JavaScript!" document.write(mystr.charAt(2)); //结果为l,注意:空格也会占一个字符 字符串上计算是从0开始 0 1 2 3 ...
indexOf()
该方法可返回某个指定的字符串值在字符串中首次出现的位置。
语法stringObject.indexOf(substring, startpos)
- substring:必填,所要检索的字符串
- startpos:选填,开始检索的位置
-
var str="I love JavaScript!" document.write(str.indexOf("I") ); document.write(str.indexOf("v") ); document.write(str.indexOf("v",8)); //结果为0 4 9 索引index=0 index=4
split()
该方法将字符串分割为字符串数组,并返回此数组。
语法:stringObject.split(separator,limit)
- separator:必填,从该参数的位置开始分割
- limit:选填,分割的次数,若不填,则无限次数分割
- 注意:如果把空字符串 ("") 用作 separator,那么 stringObject 中的每个字符之间都会被分割。
-
var mystr = "www.imooc.com"; document.write(mystr.split(".")); document.write(mystr.split(".", 2)); //结果www,imooc,com www,imooc document.write(mystr.split("")); document.write(mystr.split("", 5)); //结果w,w,w,.,i,m,o,o,c,.,c,o,m w,w,w,.,i