String 对象方法
- charAt() 返回在指定位置的字符。
var str=“Hello world!”
document.write(str.charAt(1)) //e; - concat() 连接字符串。
concat() 方法用于连接两个或多个字符串。
var str1="Hello "
var str2=“world!”
document.write(str1.concat(str2)) //Hello world! - indexOf() 检索字符串。
indexOf() 方法可返回某个指定的字符串值在字符串中首次出现的位置。
注释:indexOf() 方法对大小写敏感!如果要检索的字符串值没有出现,则该方法返回 -1。 - slice() 提取字符串的片断,并在新的字符串中返回被提取的部分。
说明:String 对象的方法 slice()、substring() 和 substr() (不建议使用)都可返回字符串的指定部分。slice() 比 substring() 要灵活一些,因为它允许使用负数作为参数。slice() 与 substr() 有所不同,因为它用两个字符的位置来指定子串,而 substr() 则用字符位置和长度来指定子串。还要注意的是,String.slice() 与 Array.slice() 相似。
var str=“Hello happy world!”
document.write(str.slice(6)) //happy world!
var str=“Hello happy world!”
document.write(str.slice(6,11)) //happy - split() 方法用于把一个字符串分割成字符串数组。
注释:如果把空字符串 ("") 用作 separator,那么 stringObject 中的每个字符之间都会被分割。String.split() 执行的操作与 Array.join 执行的操作是相反的。
var str=“How are you doing today?”
document.write(str.split(" “) + “
”)
document.write(str.split(”") + “
”)
document.write(str.split(" “,3))
How,are,you,doing,today?
H,o,w, ,a,r,e, ,y,o,u, ,d,o,i,n,g, ,t,o,d,a,y,?
How,are,you
“2:3:4:5”.split(”:") //将返回[“2”, “3”, “4”, “5”]
“|a|b|c”.split("|") //将返回["", “a”, “b”, “c”] - substring() 方法用于提取字符串中介于两个指定下标之间的字符。
var str=“Hello world!”
document.write(str.substring(3)) //lo world!
var str=“Hello world!”
document.write(str.substring(3,7)) //lo w