encode_selectively.ts (1147B)
1 /** 2 * Encodes a stringified TestQuery so that it can be placed in a `?q=` parameter in a URL. 3 * 4 * `encodeURIComponent` encodes in accordance with `application/x-www-form-urlencoded`, 5 * but URLs don't actually have to be as strict as HTML form encoding 6 * (we interpret this purely from JavaScript). 7 * So we encode the component, then selectively convert some %-encoded escape codes 8 * back to their original form for readability/copyability. 9 */ 10 export function encodeURIComponentSelectively(s: string): string { 11 let ret = encodeURIComponent(s); 12 ret = ret.replace(/%22/g, '"'); // for JSON strings 13 ret = ret.replace(/%2C/g, ','); // for path separator, and JSON arrays 14 ret = ret.replace(/%3A/g, ':'); // for big separator 15 ret = ret.replace(/%3B/g, ';'); // for param separator 16 ret = ret.replace(/%3D/g, '='); // for params (k=v) 17 ret = ret.replace(/%5B/g, '['); // for JSON arrays 18 ret = ret.replace(/%5D/g, ']'); // for JSON arrays 19 ret = ret.replace(/%7B/g, '{'); // for JSON objects 20 ret = ret.replace(/%7D/g, '}'); // for JSON objects 21 ret = ret.replace(/%E2%9C%97/g, '✗'); // for jsUndefinedMagicValue 22 return ret; 23 }