Quantcast
Channel: User HoldOffHunger - Stack Overflow
Viewing all articles
Browse latest Browse all 55

Answer by HoldOffHunger for javascript encodeURIComponent and converting spaces to + symbols

$
0
0

Just try encodeURI() and encodeURIComponent() yourself...

console.log(encodeURIComponent('@#$%^&*'));

Input: @#$%^&*. Output: %40%23%24%25%5E%26*. So, wait, what happened to *? Why wasn't this converted? TLDR: You actually want encodeRFC3986URIComponent() and encodeRFC3986URI(). Long-story...

Don't use encodeURIComponent() directly.

You should use encodeRFC3986URIComponent(), as indicated by the MDN Documentation. encodeURIComponentdoes not encode any of the following: !',()*. You need to use this other function. It will solve not only your space problems, but other character problems.

function encodeRFC3986URIComponent(str) {  return encodeURIComponent(str).replace(    /[!'()*]/g,    (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`,  );}console.log(encodeRFC3986URIComponent('@#$%^&*'));

To quote the MDN Documentation encodeURIComponent()...

To be more stringent in adhering to RFC 3986 (which reserves !, ', (, ), and *), even though these characters have no formalized URI delimiting uses, the following can be safely used: encodeRFC3986URIComponent().


Viewing all articles
Browse latest Browse all 55

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>