Skip to content

Commit fe41a00

Browse files
committed
Escape backslashes in search and replacement
1 parent 6d1b2f1 commit fe41a00

File tree

3 files changed

+9
-3
lines changed

3 files changed

+9
-3
lines changed

src/std/text.ab

+6-2
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,15 @@
11
/// Replaces all occurrences of a pattern in the content with the provided replace text.
22
pub fun replace(source, search, replace) {
3-
return "\$\{source//{search}/{replace}}"
3+
search = trust $ echo \$\{{nameof search}//\\\\/\\\\\\\\} $
4+
replace = trust $ echo \$\{{nameof replace}//\\\\/\\\\\\\\} $
5+
return trust $ echo \$\{{nameof source}//{search}/{replace}} $
46
}
57

68
/// Replaces the first occurrence of a pattern in the content with the provided replace text.
79
pub fun replace_once(source, search, replace) {
8-
return "\$\{source/{search}/{replace}}"
10+
search = replace(search, "\\", "\\\\")
11+
replace = replace(replace, "\\", "\\\\")
12+
return trust $ echo \$\{{nameof source}/{search}/{replace}} $
913
}
1014

1115
/// Replaces all occurrences of a regex pattern in the content with the provided replace text.

src/tests/stdlib/replace.ab

+2
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,9 @@ import * from "std/text"
22

33
// Output
44
// apple apple
5+
// apple
56

67
main {
78
echo replace("banana banana", "banana", "apple")
9+
echo replace("\\", "\\", "apple")
810
}

src/tests/stdlib/replace_once.ab

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
11
import * from "std/text"
22
main {
3-
echo replace_once("Succinctly", "inctly", "eeded")
3+
echo replace_once("Succinctly\\", "inctly\\", "eeded")
44
}

0 commit comments

Comments
 (0)