The JavaScript encodeURI function encodes a string as a valid URI.
var encoded_uri = encodeURI(uri);The encodeURI function returns an encoded URI by replacing all special characters with their corresponding UTF-8 escape sequences.
encodeURI() does not encode the following characters: ~ ! @ # $ & * ( ) = + ; : ' , / ?
Example:
encodeURI('~!@#$%^&*()=+[]{}\\;:\'",/?');Output:
~!@#$%25%5E&*()=+%5B%5D%7B%7D%5C;:'%22,/?The JavaScript encodeURI 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 that contains letters with diacritics:
encodeURI("http://en.wikipedia.org/wiki/Björk_Guðmundsdóttir");The output of the above code will be:
http://en.wikipedia.org/wiki/Bj%C3%B6rk_Gu%C3%B0mundsd%C3%B3ttirBelow is an example of encoding a URI that contains Cyrillic letters:
encodeURI("http://en.wikipedia.org/wiki/Алексей");The above code will yield:
http://en.wikipedia.org/wiki/%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