javascript字符串常用api使用汇总(一)

javascript字符串常用api使用汇总(一)

  • charAt
  • charCodeAt
  • fromCharCode
  • concat
  • repeat
  • startsWith
  • endsWith
  • includes
  • indexOf
  • lastIndexOf
  • slice
  • substr
  • substring
  • trim

charAt、charCodeAt、fromCharCode

按照索引获取单个字符

  let s = 'abcdefg'
  const s0 = s.charAt(0) // 获取s字符串的第一个字符,同s[0]
  const code0 = s.charCodeAt(0) // 获取s字符串的第一个字符并转换成Unicode编码
  const s1 = String.fromCharCode(97) // 把Unicode编码97转换成字符串
  console.log(s0, code0, s1, s[0]) // a  97 a a

concat、repeat

字符串拼接方法

  let s = 'abc'
  const s0 = s.concat('def') // 拼接字符串,并返回新的字符串,同 s + 'def'
  const s1 = s.repeat(2) // 返回重复的几次字符串
  console.log(s0, s1, s + 'def') // abcdef abcabc abcdef

startsWith、endsWith、includes、indexOf、lastIndexOf

判断字符串是否包含某字符或字符串

  let s = 'abcdefg'
  const b1 = s.startsWith('abc') // 判断字符串s开头是否是abc
  const b2 = s.startsWith('cd', 2) // 判断字符串s开头是否是cd,从索引为2的位置算起
  const b3 = s.startsWith('b')
  console.log(b1, b2, b3) // true true false

  const b4 = s.startsWith('fg') // 判断字符串s结尾是否为fg
  const b5 = s.startsWith('de', 5) // 判断字符串s结尾是否为de,字符串长度截取到5位
  const b6 = s.startsWith('e')
  console.log(b4, b5, b6) // true true false

  const b7 = s.includes('d') // 判断字符串s中是否有d字符
  const b8 = s.includes('df') // 判断字符串s中是否有df字符串
  const b9 = s.includes('cd') // 判断字符串s中是否有cd字符串
  console.log(b7, b8, b9) // true false true

  s = 'abcdefgabc'
  const i1 = s.indexOf('c') // 获取字符c到字符串s的位置第一个索引位置
  const i2 = s.lastIndexOf('c') // 获取字符c到字符串s的位置最后一个索引位置
  const i3 = s.indexOf('h')
  const i4 = s.lastIndexOf('h')
  // 找不到就返回-1
  console.log(i1, i2, i3, i4) // 2 9 -1 -1

slice、substr、substring

字符串切割

  let s = 'abcdefghijklmnopqrstuvwxyz'

  const s1 = s.substr(1, 4) // 获取从字符串s的1位置开始取4个字符
  const s2 = s.substring(1, 4) // 获取字符串s的1-4的字符串
  console.log(s1, s2) // bcde bcd

  const s3 = s.slice(1, 4) // 获取字符串s的1-4的字符串
  console.log(s3) // bcd

看着substringslice一样的,其实是不一样的,substring第二个参数只能填大于第一个参数和小于字符串长度,小于0则取0,大于总长度则取总长度,
最终会从参数的最小位置到最大位置获取字符串,如果两个参数相等,则返回空字符

  s.substring(1, -1) // b
  s.substring(2, -1) // ab
  s.substring(1, 999) // bcdefghijklmnopqrstuvwxyz

slice则不会自动调换参数位置,而且如果参数为负数,则会从后面倒数,如果第一个参数的位置大于了第二个参数的位置,则返回空字符串,这里的大于是不管正负最终的结果

  s.slice(-3, -1) // xy
  s.slice(23, -1) // xy
  s.slice(-1, -3) // 

trim

去除字符串两边的空白字符

  let s = '  abc  '
  const s1 = s.trim()
  console.log(s1) // abc
  // 这里是不会改变原字符串的

你可能感兴趣的:(javascript字符串常用api使用汇总(一))