iT邦幫忙

0

JS Regex相關用法

js

前言

大綱

  • 建立 Regex
  • JS replace() 取代內容
  • JS test() 回傳 Boolean (vs search())
  • JS exec() 回傳 陣列 (vs match())
  • JS split('.') 字串切割

建立 regex 方法

  • 直接宣告: JS載入即編譯,用於 pattern 不會變更時
  • 建構式: 執行才編譯,用於 pattern 會變更 (效能較差)
  // 建立正規式
  const regex = /123/
  const regexObj = new RegExp("123")

replace() 取代

  • 會建立新的字串,不影響原本的字串
  • 可用於 一般文字 取代 (只能取代一個符合項)
  • 亦可用於 regex 判斷後取代 (可通過 g 旗幟 取代多個)
  • 可以插入 取代者的中間 $1
  const str = '123 123'
  // 前為要取代的字 後為取代者
  str.replace('被取代者','取代者')

  str.replace('123','hey') // 'hey 123'
  str.replace(/123/g, 'YO!') // 'YO! YO!'
  str // '123 123'

  const str2 = '123'
  // 必須將 regex 用 () 包裹
  // $1 表 包裹內容
  // 得到 1abc 2 def3
  str2.replace(/(2)/,'abc $1 def')

test() 搜尋內容 (回傳 Boolean)

  • 類似字串方法的 search() 回傳Index值 -1未找到
  // test() 回傳 Boolean
  const str = 'abc'
   console.log(/a/.test(str)) // true
  console.log(/z/.test(str)) // false
  console.log(str.search(b)) // 1

exec() 搜尋內容

  let myString = '22.44.33'
  // 未使用 g flag [ '22', index: 0, input: '22.44.33' ]
  console.log(myString.match(/\d+/))
  // 使用 g flag [ '22', '44', '33' ]
  console.log(myString.match(/\d+/g))
  • exec() 若沒有使用 g flag 會永遠取得首項符合者(造成無限迴圈) 或者 無符合即得到 null。
  • exec() 使用 g flag,每執行一次噴出一項符合者,直到無則回傳 null
  let myString = '22.44.33.' 
  let myRegexp = /\d+/ 
  let result

  // 永遠回傳首項符合的 while 條件式 必符合 造成無限迴圈
  while (result = myRegexp.exec(myString)) {
    console.log(result, myRegexp.lastIndex)
  }
  let myString = '22.44.33' 
  let myRegexp = /\d+/g 
  let arr = []
  let result

  // 每執行一次 都會噴出下一個找到的數值
  // 當找不到數值時,回傳 null,跳出該迴圈
  while (result = myRegexp.exec(myString)) {
    arr.push(result[0]) // 將找加入該陣列
    console.log(result, myRegexp.lastIndex)
    // [ '22', index: 0, input: '22.44.33' ] 2
    // [ '44', index: 3, input: '22.44.33' ] 5
    // [ '33', index: 6, input: '22.44.33' ] 8
  }
  console.log(result) // null
  console.log(arr) // ['22','44','33']

split()

  • 若只是簡單的切割字串用此即可
  const str = '22.33.44'
  str.split('.') // [22,33,44]

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言