字符串常用方法

263 阅读2分钟

字符串

charAt(index)

index:指定位置 作用:返回指定位置的字符 注意:当参数不为整数时,返回字符串第一个字符

let s = 'cxy and jxn'

console.log(s.charAt(2)) // y

indexOf(char, startIndex)

char:必填,指定字符串 startIndex:非必填,开始寻找的位置,默认从0开始 作用:返回指定字符串在字符串中从指定位置开始首次出现的位置,找不到则返回-1

lastIndexOf(char, startIndex)

char:必填,指定字符串 startIndex:非必填,开始寻找的位置,默认从末尾开始 作用:返回指定字符串在字符串中从指定位置开始最后出现的位置,从后往前寻找,找不到则返回-1

console.log(s.indexOf('jxn', 3)) // 8

console.log(s.lastIndexOf('cxy', 4)) // 0

concat(str1, str2)

str1,str2:字符串 作用:拼接两个字符串,返回一个新的字符串,不改变原本的字符串 当然字符串拼接用 + 就可以了

let s1 = ' go shopping'
console.log(s.concat(s1)) // cxy and jxn go shopping

slice(startIndex, endIndex)

startIndex, endIndex: 开始与结束位置 作用:返回从开始到结束的子串,包括开始,不包括结束,不改变原本的字符串

console.log(s.slice(0, 3)) // cxy
console.log(s.slice()) // cxy and jxn

substr(startIndex, length)

作用:返回从startIndex开始的,长度为length的字串,不改变原本的字符串

substring(startIndex, endIndex)

作用:返回从startIndex,到endIndex结束,不包括endIndex的字串 与slice用法类似

split(char)

char:指定字符 作用:按照指定字符将字符串拆成数组,不改变原本的字符串

console.log(s.split(' ')) // ['cxy', 'and', 'jxn']
console.log(s) // cxy and jxn

match(reg)

reg:正则表达式 作用:

  1. 当正则表达式没有使用全局模式g时,返回一个数组,该数组对象如下:
  • 索引0:匹配到的第一个字符串
  • 索引index:匹配到的第一个字符串的位置
  • 索引input:字符串本身
  1. 当正则表达式没有使用全局模式g时,返回一个数组,别再有index和input,数组中依次存放匹配到的字符串
let s2 = 'cxy and cxy and cxy'
console.log(s2.match(/cxy/)) // ['cxy', index: 0, input: 'cxy and cxy']
console.log(s2.match(/cxy/g)) // ['cxy', 'cxy', 'cxy']

replace(oldstr/reg, newstr)

oldstr:要替换掉的字符串或者正则表示式 newstr:新的字符串 作用:替换字符串,返回一个新的字符串,不改变原本的字符串

console.log(s2.replace(/cxy/g, 'jxn')) // jxn and jxn and jxn

search(str/reg)

str/reg:要检索的字符串或者正则 作用:返回指定字符串或者正则匹配项的第一个位置

console.log(s2.search(/cxy/g)) // 0

toUpperCase() / toLowerCase()

作用:用于字符串转换大小写

toLocaleUpperCase() / toLocaleLowerCase()

作用:用于字符串转换大小写(与上面的方法方法仅在某些外国小语种有差别)