Skip to content

Commit f0410e0

Browse files
authored
Fix incorrectly escaped string.replace replace value (#892)
* Fix incorrectly escaped `string.replace` replace value * Add test with escaped char in search value and re-add removed test
1 parent fddc544 commit f0410e0

File tree

3 files changed

+7
-3
lines changed

3 files changed

+7
-3
lines changed

CHANGELOG.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@
44

55
- `Function.length` is supported now
66

7+
- Fixed `string.replace` incorrectly escaping some `replaceValue` characters (`().+-*?[^$`)
8+
79
## 0.34.0
810

911
- Added new `"luaTarget"` option value - `"universal"`. Choosing this target makes TypeScriptToLua generate code compatible with all supported Lua targets.

src/lualib/StringReplace.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ function __TS__StringReplace(
77
[searchValue] = string.gsub(searchValue, "[%%%(%)%.%+%-%*%?%[%^%$]", "%%%1");
88

99
if (typeof replaceValue === "string") {
10-
[replaceValue] = string.gsub(replaceValue, "[%%%(%)%.%+%-%*%?%[%^%$]", "%%%1");
10+
[replaceValue] = string.gsub(replaceValue, "%%", "%%%%");
1111
const [result] = string.gsub(source, searchValue, replaceValue, 1);
1212
return result;
1313
} else {

test/unit/builtins/string.spec.ts

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -56,10 +56,12 @@ test.each([
5656
{ inp: "hello test", searchValue: "test", replaceValue: "" },
5757
{ inp: "hello test", searchValue: "test", replaceValue: "world" },
5858
{ inp: "hello test", searchValue: "test", replaceValue: "%world" },
59+
{ inp: "hello test", searchValue: "test", replaceValue: "." },
5960
{ inp: "hello %test", searchValue: "test", replaceValue: "world" },
6061
{ inp: "hello %test", searchValue: "%test", replaceValue: "world" },
61-
{ inp: "hello test", searchValue: "test", replaceValue: (): string => "a" },
62-
{ inp: "hello test", searchValue: "test", replaceValue: (): string => "%a" },
62+
{ inp: "hello test.", searchValue: ".", replaceValue: "$" },
63+
{ inp: "hello test", searchValue: "test", replaceValue: () => "a" },
64+
{ inp: "hello test", searchValue: "test", replaceValue: () => "%a" },
6365
{ inp: "aaa", searchValue: "a", replaceValue: "b" },
6466
])("string.replace (%p)", ({ inp, searchValue, replaceValue }) => {
6567
util.testExpression`"${inp}".replace(${util.formatCode(searchValue, replaceValue)})`.expectToMatchJsResult();

0 commit comments

Comments
 (0)