The encodeURI() function encodes a Uniform Resource Identifier (URI) by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character (will only be four escape sequences for characters composed of two "surrogate" characters).

Syntax

encodeURI(URI)

Parameters

URI
A complete Uniform Resource Identifier.

Description

Assumes that the URI is a complete URI, so does not encode reserved characters that have special meaning in the URI.

encodeURI replaces all characters except the following with the appropriate UTF-8 escape sequences:

Type Includes
Reserved characters ; , / ? : @ & = + $
Unescaped characters alphabetic, decimal digits, - _ . ! ~ * ' ( )
Number sign #

Note that encodeURI by itself cannot form proper HTTP GET and POST requests, such as for XMLHTTPRequests, because "&", "+", and "=" are not encoded, which are treated as special characters in GET and POST requests. encodeURIComponent, however, does encode these characters.

Note that an URIError will be thrown if one attempts to encode a surrogate which is not part of a high-low pair, e.g.,

// high-low pair ok
console.log(encodeURI('\uD800\uDFFF'));

// lone high surrogate throws "URIError: malformed URI sequence"
console.log(encodeURI('\uD800'));

// lone low surrogate throws "URIError: malformed URI sequence"
console.log(encodeURI('\uDFFF')); 

Also note that if one wishes to follow the more recent RFC3986 for URLs, which makes square brackets reserved (for IPv6) and thus not encoded when forming something which could be part of a URL (such as a host), the following code snippet may help:

function fixedEncodeURI (str) {
    return encodeURI(str).replace(/%5B/g, '[').replace(/%5D/g, ']');
}

Specifications

Specification Status Comment
ECMAScript 3rd Edition (ECMA-262) Standard Initial definition.
ECMAScript 5.1 (ECMA-262)
The definition of 'encodeURI' in that specification.
Standard  
ECMAScript 2015 (6th Edition, ECMA-262)
The definition of 'encodeURI' in that specification.
Standard  
ECMAScript 2017 Draft (ECMA-262)
The definition of 'encodeURI' in that specification.
Draft  

Browser compatibility

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support (Yes) (Yes) (Yes) (Yes) (Yes)
Feature Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support (Yes) (Yes) (Yes) (Yes) (Yes) (Yes)

See also

Document Tags and Contributors

Tags: 
 Last updated by: fscholz,