0

How can I percent-encode a string like "ü" such that it comes out as "%C3%BC"?

Here's my current implementation:

function percentEncode(ch) {
    return '%' + ch.codePointAt(0).toString(16).toUpperCase().padStart(2,'0');
}

But that encodes it as '%FC'.

encodeURIComponent handles it correctly, but I need to encode some characters which encodeURIComponent refuses to encode, so I can't use that.

mpen
  • 272,448
  • 266
  • 850
  • 1,236

1 Answers1

0

I think I figured it out.

const UTF8_ENCODER = new TextEncoder();

function percentEncode(str) {
    return Array.from(UTF8_ENCODER.encode(str)).map(i => '%' + i.toString(16).toUpperCase().padStart(2,'0')).join('');
}

console.log(percentEncode('ü'))

credit

mpen
  • 272,448
  • 266
  • 850
  • 1,236