用Javascript编码所有特殊字符 [英] Encoding all the special characters in Javascript

查看:76
本文介绍了用Javascript编码所有特殊字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须对在这里接收到的字符串进行编码,并将其作为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 保持原样.

转义函数 可以认为已弃用,尽管正式不建议使用,但应避免使用它.


那么首选哪种编码方式?

另请参见何时应该使用转义符代替 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?

Also see When are you supposed to use escape instead of encodeURI / encodeURIComponent?

这篇关于用Javascript编码所有特殊字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆