varregex=/ab*/gvarstr='abbcdefabh'vararrwhile((arr=regex.exec(str))!==null){varmsg='Found '+arr[0]+'. 'msg+='Next match starts at '+regex.lastIndexconsole.log(msg)}// Found abb. Next match starts at 3
// Found ab. Next match starts at 9
正規表達式物件自帶方法
regex.test(測試內容) // 會回傳 true false 判斷是否匹配
regex.exec(測試內容) // 回傳陣列 匹配的全部字串/個別匹配字串/開始符合的 index 起始點/原始輸入字串
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// Match "quick brown" followed by "jumps", ignoring characters in between
// Remember "brown" and "jumps"
// Ignore case
constinputValue='The Quick Brown Fox Jumps Over The Lazy Dog'constregex=/quick\s(brown).+?(jumps)/giconstresult=regex.exec(inputValue)console.log(result)// [
// 'Quick Brown Fox Jumps',
// 'Brown',
// 'Jumps',
// index: 4,
// input: 'The Quick Brown Fox Jumps Over The Lazy Dog',
// groups: undefined
// ]