2、js中字符串常用方法

 

 

 

 

js常用方法:

1. length

2.str[index]

3.valueOf(),toString()返回string的原型值

4.charAt(index)返回子字符

5.charCodeAt(index)返回子字符串的ASCII编码

6.concat(str),  +  连接字符串

7.indexOf()返回子字符的下标

8.slice()  substring()截取字符串,返回新的字符串 

9. split()把字符串分割成数组

10.replace()返回替换后的字符串

11.match();正则匹配

 var  str='hello world';
        //字符串长度
        console.log(str.length)  //11
        //字符串也可以通过下标找到某个子字符
       console.log(str[0])       //'h'

       //valueOf(),toString()返回string型的原型值    hello world
        console.log( str.valueOf()) ;       
        console.log( str.toString());

     //charAt(index)返回子字符
     console.log(str.charAt(0));          //'h'
     //charCodeAt(index)返回子字符串的ASCII编码 
     console.log(str.charCodeAt(0));        //104    'h'所对应的ASCII码

    //concat()连接字符串
    var str1=' candy_me'
     console.log(str.concat(str1))         //'hello world candy_me'
     console.log(str+' candy_me')          //'hello world candy_me'



     //indexOf()返回子字符的下标
     console.log(str.indexOf("e"))            //1
     console.log(str.lastIndexOf("o"))      //7  最后一个o 出现的下标

     //slice()  substring()截取字符串,返回新的字符串       区别  有负数时 slice转化为字符串长度减去负数的绝对值  substring转化为0
     
     console.log(str.slice(3))                //'lo world'
      console.log(str.substring(3))            //'lo world'

       console.log(str.slice(-3))                //'rld'       (7)
      console.log(str.substring(-3))             //'hello world' (0)


      console.log(str.slice(3,7))             // 'lo w'
       console.log(str.substring(3,7))         // 'lo w'

        console.log(str.slice(3,-4))           // 'lo w'      (3,7)
       console.log(str.substring(3,-4))        //'hel'         (3,0)

       //split
       console.log(str.split()) // ['hello world']
       console.log(str.split(" ")) // ['hello','world']
       console.log(str.split(""))//  ['h','e','l','l',' ',w','o','r','l','d']
       console.log(str.split("",4))//  ['h','e','l','l']

       //split
       console.log(str.split()) // ['hello world']
       console.log(str.split(" ")) // ['hello','world']
       console.log(str.split(""))//  ['h','e','l','l',' ',w','o','r','l','d']
       console.log(str.split("",4))//  ['h','e','l','l']

       //replace
       console.log(str.replace(/world/, "tang"))         //hello tang

       str.replace("https","http")

 

 

 


 

 

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值