let regex = new RegExp('xyz', 'i') // 等價於 let regex = /xyz/i let regex = new RegExp(/xyz/i) // 等價於 let regex = /xyz/i
注意!!!es6
let regex = new RegExp(/xyz/, 'i') // 這種寫法是錯誤的
new RegExp(/abc/ig, 'i').flags // 第二個參數i會將前面的ig進行覆蓋
let str="1 plus 2 equal 3" str.match(/\d+/g) // ['1','2','3']
let str = 'nihao Jack' str.replace(/Jack/, 'Lucy') // nihao Lucy
let str = 'good body' str.search(/body/) // 5 let str = 'good body' str.search(/girl/) // -1
let str = 'good body' str.split('o') ["g", "", "d b", "dy"]
let str = /hello/; let str2 = /hello/u; str.unicode // false str2.unicode // true
let str = 'aaa_aa_a' let reg1 = /a+/g let reg2 = /a+/y reg1.exec(s) // ['aaa'] reg2.exec(s) // ['aaa'] reg1.exec(s) // ['aa'] reg2.exec(s) // null y修飾符從剩餘項的第一個位置開始(即_)因此找不到 lastIndex屬性能夠指定每次搜索的開始位置 reg2.lastsIndex = 1 reg2.exec(s) // ['aa'] 實際上y修飾符號隱含了頭部匹配的標誌^
'a1a2a3'.match(/a\d/y) // ['a1'] 'a1a2a3'.match(/a\d/gy) // ['a1','a2','a3']
const REG = /(\d{4})-(\d{2})-(\d{2})/ const matchObj = REG.exec('1999-12-31') const year = matchObj[1]; // 1999 const month = matchObj[2]; // 12 const day = matchObj[3]; // 31
問題: 只能用數字序號引用,組的順序改變,引用的時候就必須修改序號正則表達式
const REG = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/ const matchObj = REG.exec('1999-12-31') const year = matchObj.groups.year // 1999 const month = matchObj.groups.month // 12 const day = matchObj.groups.day // 31 若是具名組沒有匹配,那麼對應的groups對象屬性會是undefined
let {groups: {one, two}} = /^(?<one>.*):(?<two>.*)$/u.exec('foo:bar') console.log({one, two}) // {one: 'foo', two: 'bar'}