var fileName = 'my file(2).txt';var header = "Content-Disposition: attachment; filename*=UTF-8''" + encodeRFC5987ValueChars(fileName);
console.log(header);// logs "Content-Disposition: attachment; filename*=UTF-8''my%20file%282%29.txt"
function encodeRFC5987ValueChars (str) {return encodeURIComponent(str).// Note that although RFC3986 reserves "!", RFC5987 does not,// so we do not need to escape itreplace(/['()]/g, escape). // i.e., %27 %28 %29replace(/\*/g, '%2A').// The following are not required for percent-encoding per RFC5987,// so we can allow for a little better readability over the wire: |`^replace(/%(?:7C|60|5E)/g, unescape);}
Input: @#$%^&*. Output: %40%23%24%25%5E%26*. So, wait, what happened to *? Why wasn't this converted? It could definitely cause problems if you tried to do linux command "$string". TLDR: You actually want fixedEncodeURIComponent() and fixedEncodeURI(). Long-story...
When to use encodeURI()? Never. encodeURI() fails to adhere to RFC3986 with regard to bracket-encoding. Use fixedEncodeURI(), as defined and further explained at the MDN encodeURI() Documentation...
function fixedEncodeURI(str) {return encodeURI(str).replace(/%5B/g, '[').replace(/%5D/g, ']');}