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  // 这里是不会扭转原字符串的