1
0
mirror of https://github.com/robertkrimen/otto synced 2025-09-28 18:45:22 +08:00

Substitute undefined for failed captures in String.replace

When String.replace(...) is called with a replacement function.
Again, similar to the scenario in #2.
This commit is contained in:
Robert Krimen 2012-10-14 22:50:17 -07:00
parent b718c5ec2a
commit 235c19bd71
2 changed files with 12 additions and 1 deletions

View File

@ -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))
}

View File

@ -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) {