为什么使用regex.lastIndex和string的长度切片不同?

xdyibdwo  于 2023-08-08  发布在  其他
关注(0)|答案(1)|浏览(100)

在这里,我用正则表达式匹配一个字符串,然后用两种不同的方式切片:

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:


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

7rtdyuoh

7rtdyuoh1#

我想加match.index

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

字符串

相关问题