Skip to content

Commit

Permalink
fix: string slice and replace (#535)
Browse files Browse the repository at this point in the history
Fix string slice and replace so they work correctly with utf8
characters.

Fixes #534
  • Loading branch information
stevenh authored Nov 4, 2024
1 parent aefc75a commit c136deb
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 3 deletions.
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

0 comments on commit c136deb

Please sign in to comment.