Skip to content

Commit 217ef16

Browse files
committed
fix: Bug when encoding more than one left/right paren in string literal
Per the docs, String.replace(target,dest) will only replace the first occurrence when target is a string. A regex is needed to do a global search and replace. One odd thing I found when testing is that these worked, and replaced all occurrences: ret.replace(",", "%x2C") ret.replace(":", "%x3A") But these did not, and requred a regex to get all occurrences: ret.replace("(", "%x28") ret.replace(")", "%x28") I used a regex for all regardless.
1 parent df7f249 commit 217ef16

File tree

2 files changed

+14
-4
lines changed

2 files changed

+14
-4
lines changed

src/JsonURL.js

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,10 @@
2727

2828
const rx_decode_space = /\+/g;
2929
const rx_encode_pctspace = /%20/g;
30+
const rx_encode_comma = /,/g;
31+
const rx_encode_colon = /:/g;
32+
const rx_encode_lparen = /\(/g;
33+
const rx_encode_rparen = /\)/g;
3034
const rx_encode_space = / /g;
3135

3236
//
@@ -289,10 +293,10 @@ function parseStringLiteral(text, pos, end, removeQuotes) {
289293
function encodeStringLiteral(text) {
290294
let ret = encodeURIComponent(text);
291295
ret = ret.replace(rx_encode_pctspace, "+");
292-
ret = ret.replace(",", "%x2C");
293-
ret = ret.replace(":", "%x3A");
294-
ret = ret.replace("(", "%x28");
295-
ret = ret.replace(")", "%x29");
296+
ret = ret.replace(rx_encode_comma, "%x2C");
297+
ret = ret.replace(rx_encode_colon, "%x3A");
298+
ret = ret.replace(rx_encode_lparen, "%x28");
299+
ret = ret.replace(rx_encode_rparen, "%x29");
296300

297301
return ret;
298302
}

test/stringify.test.js

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,12 @@ test.each([
5454
["a b c", "a+b+c", "a+b+c"],
5555
["a,b", "'a,b'", "a%2Cb"],
5656
["a,b c", "'a,b+c'", "a%2Cb+c"],
57+
["a,b,c", "'a,b,c'", "a%2Cb%2Cc"],
58+
["a:b:c", "'a:b:c'", "a%3Ab%3Ac"],
59+
["((()))", "'((()))'", "%x28%x28%x28%x29%x29%x29"],
60+
[":::", "':::'", "%3A%3A%3A"],
61+
[",,,", "',,,'", "%2C%2C%2C"],
62+
[" ", "+++", "+++"],
5763
["Bob & Frank", "Bob+%26+Frank", "Bob+%26+Frank"],
5864
["'hello", "%27hello", "'hello"],
5965
])("JsonURL.stringify(%p)", (value, expected, expectedISL) => {

0 commit comments

Comments
 (0)