Fastest way to encode cyrillic letters for url

Haradzieniec picture Haradzieniec · Oct 9, 2013 · Viewed 16k times · Source

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:

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?

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.

Answer

Butt4cak3 picture Butt4cak3 · Oct 9, 2013

The function you're searching for is 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("%D0%91%D0%B5%D0%BB%D0%B0%D1%80%D1%83%D1%81%D1%8C");
// returns "Беларусь"