RFC 5987 Encoder

by Cristiano Oliveira

HTML

<pre id="imgenc"></pre>
<pre id="imgdec"></pre>
<img id="imgurl" src="">

JavaScript

var imageUrl = 'https://cdn.stmsrv.com/multi/7000/logo_zuc8j9s.png';

var imageEnc = encodeRFC5987ValueChars(imageUrl);
var imageDec = decodeURIComponent(imageEnc);

document.getElementById("imgurl").src = imageDec;
document.getElementById("imgenc").innerText = imageEnc;
document.getElementById("imgdec").innerText = imageDec;

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);
}