如何在 JavaScript 中正确编码 URL?
我正在开发一个浏览器插件,它将当前页面的 URL 或任何选定的链接作为参数并将其发送到我们的服务器。 当 url 中存在基本拉丁字母的字符时(例如 http://en.wikipedia.org/ wiki/Vehicle),该插件工作正常。但是,当 URL 包含其他字母表中的字符时,例如 http://ru.wikipedia.org/wiki/Коляска 该插件不起作用,我使用 encodeURIComponent
方法,但这似乎并不能解决问题。有什么想法吗?
谢谢,
奥利维尔。
I am working on a browser plugin that takes the URL of the current page or any selected link as a parameter and send it to our server.
When characters of the basic latin alphabet are present in the url (like http://en.wikipedia.org/wiki/Vehicle), the plugin works fine. However, when the URL contains characters from another alphabet such as http://ru.wikipedia.org/wiki/Коляска the plugin does not work, I do use the encodeURIComponent
method but that does not seem to solve the issue. Any idea?
Thanks,
Olivier.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可能想使用
encodeURI
/decodeURI
,如果您尝试获取包含非 ASCII 字符的完整 URI,并将其转换为其编码形式。它们保留特殊的 URI 字符,例如:
和/
,而不是转义它们;它仅转义非 ASCII 字符和 URI 中无效的字符。因此,它们的作用本质上与在地址栏中键入内容或将 URI 放入中相同(尽管浏览器之间的行为可能有所不同,并且并不完全相同)。
encodeURIComponent
旨在仅对 URI 的单个组件进行编码,替换 URI 中有意义的特殊字符,以便您可以将该组件用作较长 URI 中的查询参数或路径组件。You probably want to use
encodeURI
/decodeURI
, if you are trying to take a full URI with non-ASCII characters and translate it into its encoded form. These preserve special URI characters, such as:
and/
, instead of escaping them; it only escapes non-ASCII characters and characters that are invalid in URIs. Thus, they do essentially the same thing as typing in the address bar or putting a URI in an<a href="...">
(though the behavior might vary somewhat between browser, and isn't exactly the same).encodeURIComponent
is intended for encoding only a single component of a URI, replacing special characters that are meaningful in URIs, so that you can use the component as a query parameter or path component in a longer URI.这个说它涵盖UTF-8。 http://www.webtoolkit.info/javascript-url-decode-encode。 html。可能会解决你的问题
This one says it covers UTF-8. http://www.webtoolkit.info/javascript-url-decode-encode.html. Might solve your problem