字符串的常用方法

charAt

作用:返回字符串(index)为下标
参数:str.charAt(index)

    let str='hellow world'
    console.log(str.charAt(2))    

charCodeAt

作用:返回字符串的uniconde编码,index在取值范围之内
参数:str.charCodeAt(''')

     let str='hellow world'
     console.log(str.charCodeAt('w'))     //104     a-z:97-122

fromCharCode

作用:根据unucinde编码返回字符串
参数:str.fromCharCode('102')

   var a = 104
   console.log(str.fromCharCode)  //h

indexOf

作用:查找指定元素的位置
参数:str.indexOf(item,start) //item检查的值,start在哪里检查一般不写
返回值:返回第一次找到的索引,未找到返回-1
是否改变原数组:不改变

   let str='1,23,4325345,1231'
   console.log(arr.indexOf(1231))   //输出结果为3

lastIndexOf

作用:查找指定元素最后出现的位置
参数:arr.indexOf(item,start) //item检查的值,start在哪里检查一般不写
返回值:返回第一次找到的索引,未找到返回-1
是否改变原数组:不改变

  let arr=[1,1,1,1,1]
    arr.lastIndexOf(1)  //输出结果为5

substring

作用:字符串截取
参数:str.substring(start,end) start||end不算本身

    let str='hellow world'
    let a=str.substring(1,2) 
   console.log(a)    //e

slice

作用:字符串截取
参数:str.slice(start,end) start||end不算本身

    let str='hellow world'
    let a=str.substring(1,2) 
   console.log(a)    //e

substr

作用:截取字符串
参数:str.substr(start,end) start不算本身end算本身

    let str='hellow world'
    let a=str.substr(1,2)  
    console.log(a)    //el

replace

作用:替换原有的内容
参数:str.replace('被替换的','替换的内容')

    let str='hellow world'
    let a=str.replace('hellow ','xiao')
    console.log(a)   //xiao world    

split

作用:字符串分割成数组
参数:str.split()

     let str='1,2,3,4'
     let arr=str.split()
      console.log(arr)   //[1,2,3,4]

search

作用:查找str与一个正则表达式是否匹配,如果匹配成功,则返回正则表达式在在字符串首次匹配项的索引
参数:str.search(regexp)

    let str='i love my home'
    str.seach('java')  //10

match

作用: 返回一个包含匹配结果的数组,如果没有匹配项,则返回null。如果参数传入的是一个非正则表达式对象,则会使用new RegExp隐式的将其转换为正则表达式对象
参数:str.match('查找的东西')

    let str='i love my home'
    console.log(''home') //["home", index: 10, input: "i love my home", groups: undefined

trim

作用:去除字符串开头和尾部的空白字符
参数:str.trim()

    let str='hellow  world'
    let a=str.trim()

toLowerCase()

作用:把字符串转换为小写
参数:str.toLowerCase()

   let str='HELLOW WORLD'
   let a=str.toLowerCase()
   console.log(a)               //'hellow world'

toUpperCase()

let str=‘hellow world’
let a=str.toUpperCase()
console.log(a) //HELLOW WORLD

   let str=''hellow world"
   let a=str.toLowerCase()
   console.log(a)               //'HELLOW WORLD

toString

作用:将number强制转换为string类型
参数:123.toString()

    var a = 123;
    a.toString()  //'123'
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容