The JavaScript encodeURIComponent function encodes a string as a valid URI component.
var encoded_uri_comp = encodeURIComponent(uri_component);The encodeURIComponent function returns an encoded URI component by replacing all special characters with their corresponding UTF-8 escape sequences.
encodeURIComponent does not encode the following characters: ~ ! * ( ) '
Example:
encodeURIComponent('~!@#$%^&*()=+[]{}\\;:\'",/?');Output:
~!%40%23%24%25%5E%26*()%3D%2B%5B%5D%7B%7D%5C%3B%3A'%22%2C%2F%3FThe JavaScript encodeURIComponent function can be used to encode special reserved characters and other non-ASCII characters such as letters with diacritics or from the Cyrillic alphabet.
Here's an example of encoding a URI component that contains letters with diacritics:
encodeURIComponent("Björk Guðmundsdóttir");The above code will output:
Bj%C3%B6rk%20Gu%C3%B0mundsd%C3%B3ttirBelow is an example of encoding a URI that contains Cyrillic letters:
encodeURIComponent("Алексей");The output of the above code will be:
%D0%90%D0%BB%D0%B5%D0%BA%D1%81%D0%B5%D0%B9If you see a typo, want to make a suggestion or have anything in particular you'd like to know more about, please drop us an e-mail at hello at diveintojavascript dot com.
Copyright © 2010-2011 Dive Into JavaScript