The JavaScript encodeURI Function

The JavaScript encodeURI function encodes a string as a valid URI.

Syntax

var encoded_uri = encodeURI(uri);

Parameters

uri
A complete URI to be encoded

Description

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,/?

JavaScript encodeURI Examples

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.

Encoding letters with diacritics

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%B3ttir

Encoding Cyrillic letters

Below 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%B9

See also

If 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-2013 Dive Into JavaScript