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. encodeURIComponent
does 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()
.
+
characters. – Sequestration