Are there any equivalent JavaScript functions for Python’s urllib.parse.quote() and urllib.parse.unquote()?
The closest I’ve come across are encodeURI()/encodeURIComponent() and escape() (and their corresponding un-encoding functions), but they don’t encode/decode the same set of special characters as far as I can tell.
OK, I think I’m going to go with a hybrid custom set of functions:
Encode: Use encodeURIComponent(), then put slashes back in.
Decode: Decode any %hex values found.
Here’s a more complete variant of what I ended up using (it handles Unicode properly, too):
Note that if you don’t need “safe” characters when encoding (
'/'by default in Python), then you can just use the built-inencodeURIComponent()anddecodeURIComponent()functions directly.Also, if there are Unicode characters (i.e. characters with codepoint >= 128) in the string, then to maintain compatibility with JavaScript’s
encodeURIComponent(), the Pythonquote_url()would have to be:And
unquote_url()would be: