用Javascript编码所有特殊字符

编程入门 行业动态 更新时间:2024-10-09 02:21:57
本文介绍了用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 保持原样.

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

那么首选哪种编码方式?

  • 对于整个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编码所有特殊字符

本文发布于:2023-11-27 18:44:32,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1639165.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:特殊字符   Javascript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!