Skip to content

Commit c136deb

Browse files
authored
fix: string slice and replace (#535)
Fix string slice and replace so they work correctly with utf8 characters. Fixes #534
1 parent aefc75a commit c136deb

File tree

2 files changed

+8
-3
lines changed

2 files changed

+8
-3
lines changed

builtin_string.go

+7-3
Original file line numberDiff line numberDiff line change
@@ -254,7 +254,9 @@ func builtinStringReplace(call FunctionCall) Value {
254254
argumentList[index] = Value{}
255255
}
256256
}
257-
argumentList[matchCount+0] = intValue(match[0])
257+
// Replace expects rune offsets not byte offsets.
258+
startIndex := utf8.RuneCountInString(target[0:match[0]])
259+
argumentList[matchCount+0] = intValue(startIndex)
258260
argumentList[matchCount+1] = stringValue(target)
259261
replacement := replace.call(Value{}, argumentList, false, nativeFrame).string()
260262
result = append(result, []byte(replacement)...)
@@ -394,16 +396,18 @@ func builtinStringSplit(call FunctionCall) Value {
394396
}
395397
}
396398

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

401405
length := int64(len(target))
402406
start, end := rangeStartEnd(call.ArgumentList, length, false)
403407
if end-start <= 0 {
404408
return stringValue("")
405409
}
406-
return stringValue(target[start:end])
410+
return stringValue(string(target[start:end]))
407411
}
408412

409413
func builtinStringSubstring(call FunctionCall) Value {

string_test.go

+1
Original file line numberDiff line numberDiff line change
@@ -331,6 +331,7 @@ func TestString_slice_unicode(t *testing.T) {
331331
test(`"uñiçode".slice(0,11)`, "uñiçode")
332332
test(`"uñiçode".slice(0,-1)`, "uñiçod")
333333
test(`"uñiçode".slice(-1,11)`, "e")
334+
test(`"发送 213123".slice(0,2)`, "发送")
334335
})
335336
}
336337

0 commit comments

Comments
 (0)