JS Regex相关用法

前言

exec() 看得雾煞煞 OTZ[偷米骑巴哥]正规式苦手超入门pjchender私房菜

大纲

建立 RegexJS 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() 搜寻内容

速度会较 test() 慢类似字串方法的 match(),皆回传阵列stack overflow 参考资料
  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]

关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章