From 373ff54384526e8336b5b597619d0923a4a83ae0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Luka=20Zakraj=C5=A1ek?= Date: Mon, 14 Jun 2021 20:17:06 +0200 Subject: [PATCH] fix: Incorrect groups offsets if lastIndex is set (#393) --- regexp_test.go | 15 +++++++++++++++ type_regexp.go | 6 ++++-- 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/regexp_test.go b/regexp_test.go index 8e65ee4..e8559c0 100644 --- a/regexp_test.go +++ b/regexp_test.go @@ -121,6 +121,21 @@ func TestRegExp_exec(t *testing.T) { [ ghi, lastIndex ]; `, "3,7") + test(` + abc = /(\d)?(s)/g; + def = 's'; + ghi = abc.exec(def); + [ ghi[1] === undefined, ghi[2] === 's' ]; + `, "true,true") + + test(` + abc = /(\d)?(s)/g; + def = '%s'; + abc.lastIndex = 1; + ghi = abc.exec(def); + [ ghi[1] === undefined, ghi[2] === 's' ]; + `, "true,true") + test(` var abc = /[abc](\d)?/.exec("a0 b c1 d3"); [ abc.length, abc.input, abc.index, abc ]; diff --git a/type_regexp.go b/type_regexp.go index 57fe316..30b22fd 100644 --- a/type_regexp.go +++ b/type_regexp.go @@ -108,8 +108,10 @@ func execRegExp(this *_object, target string) (match bool, result []int) { endIndex := int(lastIndex) + result[1] // We do this shift here because the .FindStringSubmatchIndex above // was done on a local subordinate slice of the string, not the whole string - for index, _ := range result { - result[index] += int(startIndex) + for index, offset := range result { + if offset != -1 { + result[index] += int(startIndex) + } } if global { //this.defineProperty("lastIndex", toValue_(endIndex), 0111, true)