为何使用regex.lastIndex与字符串长度进行切片的结果不同?
正则匹配后切片结果异常的原因
代码示例
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:
问题原因
核心是没搞懂String.slice()的参数规则:
slice(start, end)的第二个参数是结束位置的索引,不是要截取的字符长度。- 第一次匹配时,
match.index是0,用word.length(2)作为结束索引,slice(0,2)刚好截取索引0到2的字符,得到hi,结果正确。 - 第二次匹配时,
match.index是3(第二个hi从字符串的第3位开始),这时候你还是传word.length(2)作为结束索引,相当于调用slice(3,2)。当起始索引大于结束索引时,slice会直接返回空字符串,这就是第二次结果为空的原因。
正确写法
如果想用字符长度来截取,应该把结束索引设为match.index + word.length:
console.log('slice with correct length:', string.slice(match.index, match.index + word.length))
这样第二次调用就是slice(3, 5),能正确截取到第二个hi。
内容的提问来源于stack exchange,提问作者Ooker
相关产品推荐
相关产品推荐

