我必须对在这里接收到的字符串进行编码,并将其作为URL参数传递,这样我不相信我可以传递/或paranthesis(因此考虑到我拥有以下字符串
基韦斯特/佛罗里达州(FL)我正在尝试以下
encodeURIComponent("KEY WEST/Florida(FL)")"KEY%20WEST%20%2F%20Florida(FL)"转义符("KEY WEST/Florida(FL)")"KEY%20WEST%20/%20Florida%28FL%29"它们都不对字符串进行编码,我可以稍后在我的代码中对其进行解码,因为第一个保留(),第二个保留/
我该如何一次拍摄并在以后需要时将其解码?
还似乎已经不建议使用escape(),因此首选哪种编码方式?
解决方案对于URL编码,应使用 encodeURI 和 encodeURIComponent 函数.
encodeURI 仅对特殊字符进行编码,而 encodeURIComponent 也对URL中具有含义的字符进行编码,例如,它用于对查询字符串进行编码.
括号是可以的(如在此所述),但是允许在URL中的任何位置对它们进行编码,这就是> encodeURIComponent 保持原样.
转义函数 可以认为已弃用,尽管正式不建议使用,但应避免使用它.
那么首选哪种编码方式?
- 对于整个URL, encodeURI
- 对于网址部分,例如片段的查询字符串, encodeURIComponent
另请参见何时应该使用转义符代替 encodeURI / encodeURIComponent ?
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?
- 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?
更多推荐
用Javascript编码所有特殊字符
发布评论