js正則表示式高階用法
阿新 • • 發佈:2021-09-15
1. 宣告詞量
1. 正向宣告
指定匹配模式後面的字元必須被匹配,但又不返回這些字元。語法格式如下:
匹配模式 (?= 匹配條件)
let regex = /(\d)+(?=d)/g
let str = 'd123abc456def'
let a;
while(a = regex.exec(str)){
console.log(a) // expect output: [ '456', '6', index: 7, input: 'd123abc456def', groups: undefined ]
}
2. 反向宣告
與正向宣告匹配相反,指定接下來的字元都不必被匹配。語法格式如下:
匹配模式(?! 匹配條件)
let regex = /(\d){3}(?!d)/g
let str = 'd123abc456def'
let a;
while(a = regex.exec(str)){
console.log(a) // expect output: [ '123', '3', index: 1, input: 'd123abc456def', groups: undefined ]
}
2. 多次匹配:
想要用exec方法在一個字串裡面多次匹配上某個正則表示式,需要使用while迴圈,如下:
let regex = /\d+/g let str = 'd123abc456def' let a; while(a = regex.exec(str)){ console.log(a) } // expected output : // [ '123', index: 1, input: 'd123abc456def', groups: undefined ] // [ '456', index: 7, input: 'd123abc456def', groups: undefined ]
3. 這裡附加一下正則表示式的基本用法:
- test() 方法用於檢測一個字串是否匹配某個模式,如果字串中含有匹配的文字,則返回 true,否則返回 false。
var reg = /(\d{4})-(\d{2})-(\d{2})/;
var dateStr = '2018-04-18';
reg.test(dateStr); //true
下面的方法都是字串相關的方法:
- match()方法用於在字串內檢索指定的值,或找到一個或多個正則表示式的匹配。該方法類似 indexOf() 和 lastIndexOf(),但是它返回指定的值,而不是字串的位置。
let regex = /\d+/g let str = 'd123abc456def' console.log(str.match(regex)) // [ '123', '456' ]
- replace() 字串替換,並返回替換後的結果(原字串不做修改):
let regex = /\d+/g
let str = 'd123abc456def'
console.log(str.replace(regex,'HELLO')) // dHELLOabcHELLOdef
- search() 方法。 用於檢索字串中指定的子字串,或檢索與正則表示式相匹配的子字串,並返回子串的起始位置。
let regex = /\d+/g
let str = 'd123abc456def'
console.log(str.search(regex)) // 1
console.log(str.search(regex)) // 1