diff --git a/builtin.go b/builtin.go index ad8640a..bb58768 100644 --- a/builtin.go +++ b/builtin.go @@ -412,7 +412,11 @@ func builtinString_replace(call FunctionCall) Value { argumentList := make([]Value, matchCount + 2) for index := 0; index < matchCount; index++ { offset := 2 * index - argumentList[index] = toValue(target[match[offset]:match[offset+1]]) + if match[offset] != -1 { + argumentList[index] = toValue(target[match[offset]:match[offset+1]]) + } else { + argumentList[index] = UndefinedValue() + } } argumentList[matchCount + 0] = toValue(match[0]) argumentList[matchCount + 1] = toValue(target) @@ -432,9 +436,11 @@ func builtinString_replace(call FunctionCall) Value { if lastIndex != len(target) { result = append(result, target[lastIndex:]...) } + if global && searchObject != nil { searchObject.Put("lastIndex", toValue(lastIndex), true) } + return toValue(string(result)) } diff --git a/otto_test.go b/otto_test.go index 5482ce5..39c39f6 100644 --- a/otto_test.go +++ b/otto_test.go @@ -1558,6 +1558,11 @@ func TestString_replace(t *testing.T) { `, "_undefined_undefined_") test(`"b".replace(/(a)?(b)?/, "_$1_")`, "__") + test(` + "b".replace(/(a)?(b)?/, function(a, b, c, d, e, f){ + return [a, b, c, d, e, f] + }) + `, "b,,b,0,b,") } func TestString_search(t *testing.T) {