Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: string slice and replace #535

Merged
merged 1 commit into from
Nov 4, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 7 additions & 3 deletions builtin_string.go
Original file line number Diff line number Diff line change
Expand Up @@ -254,7 +254,9 @@ func builtinStringReplace(call FunctionCall) Value {
argumentList[index] = Value{}
}
}
argumentList[matchCount+0] = intValue(match[0])
// Replace expects rune offsets not byte offsets.
startIndex := utf8.RuneCountInString(target[0:match[0]])
argumentList[matchCount+0] = intValue(startIndex)
argumentList[matchCount+1] = stringValue(target)
replacement := replace.call(Value{}, argumentList, false, nativeFrame).string()
result = append(result, []byte(replacement)...)
Expand Down Expand Up @@ -394,16 +396,18 @@ func builtinStringSplit(call FunctionCall) Value {
}
}

// builtinStringSlice returns the string sliced by the given values
// which are rune not byte offsets, as per String.prototype.slice.
func builtinStringSlice(call FunctionCall) Value {
checkObjectCoercible(call.runtime, call.This)
target := call.This.string()
target := []rune(call.This.string())

length := int64(len(target))
start, end := rangeStartEnd(call.ArgumentList, length, false)
if end-start <= 0 {
return stringValue("")
}
return stringValue(target[start:end])
return stringValue(string(target[start:end]))
}

func builtinStringSubstring(call FunctionCall) Value {
Expand Down
1 change: 1 addition & 0 deletions string_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -331,6 +331,7 @@ func TestString_slice_unicode(t *testing.T) {
test(`"uñiçode".slice(0,11)`, "uñiçode")
test(`"uñiçode".slice(0,-1)`, "uñiçod")
test(`"uñiçode".slice(-1,11)`, "e")
test(`"发送 213123".slice(0,2)`, "发送")
})
}

Expand Down