Encoding All The Special Characters In Javascript
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
Solution 1:
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?
- For entire URLs,
encodeURI
- For URL parts, e.g. query string of fragment,
encodeURIComponent
Also see When are you supposed to use escape instead of encodeURI
/ encodeURIComponent
?
Post a Comment for "Encoding All The Special Characters In Javascript"