js中的常用字符串操作

String 对象方法

  1. charAt() 返回在指定位置的字符。
    var str=“Hello world!”
    document.write(str.charAt(1)) //e;
  2. concat() 连接字符串。
    concat() 方法用于连接两个或多个字符串。
    var str1="Hello "
    var str2=“world!”
    document.write(str1.concat(str2)) //Hello world!
  3. indexOf() 检索字符串。
    indexOf() 方法可返回某个指定的字符串值在字符串中首次出现的位置。
    注释:indexOf() 方法对大小写敏感!如果要检索的字符串值没有出现,则该方法返回 -1。
  4. 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
  5. 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”]
  6. substring() 方法用于提取字符串中介于两个指定下标之间的字符。
    var str=“Hello world!”
    document.write(str.substring(3)) //lo world!
    var str=“Hello world!”
    document.write(str.substring(3,7)) //lo w
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值