为什么使用 regex.lastIndex 和字符串长度进行切片不同?

Why are slicing with regex.lastIndex and with string's length different?

提问人:Ooker 提问时间:7/11/2023 更新时间:7/11/2023 访问量:30

问:

在这里,我将字符串与正则表达式匹配,然后以 2 种不同的方式对其进行切片:

const string = 'hi hi'
const word = 'hi'
const regex = new RegExp(word, 'gi');
while (match = regex.exec(string)) {
    console.log(match.index, regex.lastIndex)
    console.log('slice with regex.lastIndex:', string.slice(match.index, regex.lastIndex))
    console.log('slice with string\'s length:', string.slice(match.index, word.length))
}

结果:

0 2
slice with regex.lastIndex: hi
slice with string's length: hi
3 5
slice with regex.lastIndex: hi
slice with string's length: 

为什么第二次切片不起作用?

JavaScript 正则表达 式切片

评论


答:

-2赞 Ooker 7/11/2023 #1

我想念添加match.index

console.log('slice with string\'s length:', string.slice(match.index, match.index + word.length))