RegExp 对象方法 exec()
以下是一段JavaScript代码,演示了如何使用RegExp对象的exec()方法:
const arr = ['ezlost', 'losthome', 'meller', 'cool', 'eat']
let pett = /e/g
arr.forEach(function(a) {
console.log(pett.exec(a))
})
运行结果:
const arr = ['ezlost', 'losthome', 'meller', 'cool', 'eat']
let pett = /e/g
arr.forEach(function(a) {
console.log(pett.exec(a))
})
// ["e", index: 0, input: "ezlost", groups: undefined]
// ["e", index: 7, input: "losthome", groups: undefined]
// null
// null
// ["e", index: 0, input: "eat", groups: undefined]
显而易见,其中'meller'没有被识别。但这是为什么呢?
其实exec()方法在执行完会将pett的lastIndex指向当前位置的下一位。
为了验证这一点,我们可以再次运行代码,并打印出每次调用exec()方法后的lastIndex值:
arr.forEach(function(a) {
console.log(pett.exec(a));
console.log(pett.lastIndex);
})
// ["e", index: 0, input: "ezlost", groups: undefined]
// 1
// ["e", index: 7, input: "losthome", groups: undefined]
// 8
// null
// 0
// null
// 0
// ["e", index: 0, input: "eat", groups: undefined]
// 1
由上运行结果可得出:当运行到losthome时,'e'的位置是7,这时pett.lastIndex就指向了8,所以后续字符串中即使存在'e',由于lastIndex已经超过了字符串的长度,exec()方法也会返回null。
这里有一个个人的解决方案,就是将let pett = /e/g的全局标志g去掉:
let pett = /e/
或者使用match方法:
const arr1 = ['ezlost', 'losthome', 'meller', 'cool', 'eat']
let pett1 = /e/
arr1.forEach(function(a) {
let b = pett1.exec(a)
console.log(b)
console.log(pett1.lastIndex)
})
// ["e", index: 0, input: "ezlost", groups: undefined]
// 0
// ["e", index: 7, input: "losthome", groups: undefined]
// 0
// ["e", index: 1, input: "meller", groups: undefined]
// 0
// null
// 0
// ["e", index: 0, input: "eat", groups: undefined]
// 0