javascript 为 url 编码西里尔字母的最快方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19272494/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Fastest way to encode cyrillic letters for url
提问by Haradzieniec
If you copy the link below into the browser
如果您将以下链接复制到浏览器中
http://be.wikipedia.org/wiki/Беларусь
it will show the Wiki article. But once you want to copy that link (or any other link that contains cyrillic symbols) from the browser url into the notepad, you'll get something like this:
它将显示维基文章。但是,一旦您想将该链接(或任何其他包含西里尔符号的链接)从浏览器 url 复制到记事本中,您将得到如下内容:
http://be.wikipedia.org/wiki/%D0%91%D0%B5%D0%BB%D0%B0%D1%80%D1%83%D1%81%D1%8C
You can click on any link in the wikipedia that contains cyrillic letters in the text and try to copy it into the Notepad.
您可以单击维基百科中文本中包含西里尔字母的任何链接,然后尝试将其复制到记事本中。
So, my question is:
所以,我的问题是:
What's the most correct or fastest way to convert any text that contains cyrillic word Беларусь
into %D0%91%D0%B5%D0%BB%D0%B0%D1%80%D1%83%D1%81%D1%8C
or any other text into such type of code so it is a valid part of the URL?
Is there a special javascript function for that purpose?
什么是包含西里尔字母词的任何文本转换最正确或最快捷的方式Беларусь
进入%D0%91%D0%B5%D0%BB%D0%B0%D1%80%D1%83%D1%81%D1%8C
或任何其他文本到这种类型的代码,所以它是URL的有效部分?是否有一个特殊的 javascript 函数用于这个目的?
I've checked, it is actually : cyrillic capital letter Б = (hex) D0 91 for UTF-8. That's why it is %D0%91 and so on.
我检查过,它实际上是:西里尔大写字母 Б = (hex) D0 91 for UTF-8。这就是为什么它是 %D0%91 等等。
采纳答案by Butt4cak3
The function you're searching for is encodeURIComponent
.
您要搜索的功能是encodeURIComponent
。
encodeURIComponent("Беларусь");
// returns "%D0%91%D0%B5%D0%BB%D0%B0%D1%80%D1%83%D1%81%D1%8C"
Its counterpart is decodeURIComponent
which reverses this process.
它的对应物是decodeURIComponent
逆转这个过程。
decodeURIComponent("%D0%91%D0%B5%D0%BB%D0%B0%D1%80%D1%83%D1%81%D1%8C");
// returns "Беларусь"