The JavaScript encodeURIComponent Function

The JavaScript encodeURIComponent function encodes a string as a valid URI component.

Syntax

var encoded_uri_comp = encodeURIComponent(uri_component);

Parameters

uri_component
A URI component to be encoded

Description

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%3F

JavaScript encodeURIComponent Examples

The 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.

Encoding letters with diacritics

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

Encoding Cyrillic letters

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