I have to encode the string that I receive here and pass it as a URL parameter so I don't believe I can pass either / or a paranthesis ( so considering I have the following string
KEY WEST / Florida(FL)
I am trying the following
encodeURIComponent("KEY WEST / Florida(FL)")
"KEY%20WEST%20%2F%20Florida(FL)"
escape("KEY WEST / Florida(FL)")
"KEY%20WEST%20/%20Florida%28FL%29"
Neither of them are encoding the string which I can decode later in my code as the first one is keeping the () and the second one is keeping the /
How do I do this in one shot and at a later time decode it when needed?
Also it seems like escape() has been deprecated so which way to do the encoding is preferred?
For URL encoding, encodeURI
and encodeURIComponent
functions should be used.
encodeURI
encodes only special characters, while encodeURIComponent
also encodes characters that have a meaning in the URL, so it is used to encode query strings, for example.
Parentheses are (as explained here), however, allowed anywhere in the URL without encoding them, that's why encodeURIComponent
leaves them as-is.
The escape
function can be considered deprecated, and although it officially isn't, it should be avoided.
so which way to do the encoding is preferred?
encodeURI
encodeURIComponent
Also see When are you supposed to use escape instead of encodeURI
/ encodeURIComponent
?