博客 / 詳情

返回

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
  // 這裏是不會改變原字符串的
user avatar 1023 頭像 lanlanjintianhenhappy 頭像 peter-wilson 頭像 ivyzhang 頭像 huishou 頭像 shaochuancs 頭像 uncletong_doge 頭像 tingzhong666 頭像 201926 頭像 lesini 頭像 niumingxin 頭像 79px 頭像
33 位用戶收藏了這個故事!

發佈 評論

Some HTML is okay.