Skip to content

Instantly share code, notes, and snippets.

@brettz9
Last active November 5, 2016 22:58
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brettz9/8752120 to your computer and use it in GitHub Desktop.
Save brettz9/8752120 to your computer and use it in GitHub Desktop.
encodeRFC5987ValueChars
// Posted at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent
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 it
replace(/['()]/g, escape). // i.e., %27 %28 %29
replace(/\*/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);
}
function encodeRFC5987ValueChars ($str) {
// See http://tools.ietf.org/html/rfc5987#section-3.2.1
// For better readability within headers, add back the characters escaped by rawurlencode but still allowable
// Although RFC3986 reserves "!" (%21), RFC5987 does not
return preg_replace_callback('@%(2[1346B]|5E|60|7C)@', function ($matches) { // !#$&+^`| are the characters matched here, respectively
return chr('0x' . $matches[1]);
}, rawurlencode($str));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment