Javascript - URI-Encoding Methods

Introduction

The encodeURI() and encodeURIComponent() methods can encode URIs.

The URI-encoding methods encode the URIs so that a browser can accept, replacing all invalid characters with a special UTF-8 encoding.

The encodeURI() method works on an entire URI, whereas encodeURIComponent() works solely on a segment of a URI.

encodeURI() does not encode special characters that are part of a URI, such as the colon, forward slash, question mark, and pound sign, whereas encodeURIComponent() encodes every non-standard character it finds.

Demo

var uri = "http://www.book2s.com/illegal value.htm#start";
console.log(encodeURI(uri));
console.log(encodeURIComponent(uri));

Result

encodeURI() can be used on full URIs, whereas encodeURIComponent() can be used only on strings that are appended to the end of an existing URI.

The decodeURI() method decodes only characters that would have been replaced by using encodeURI().

decodeURIComponent() decodes all characters encoded by encodeURIComponent(), and it decodes all special values.

Demo

var uri = "http%3A%2F%2Fwww.book2s.com%2Fillegal%20value.htm%23start";
console.log(decodeURI(uri));
console.log(decodeURIComponent(uri));

Result

escape() and unescape() methods are deprecated in the ECMA-262 third edition.

The URI methods are preferable, because they encode all Unicode characters, whereas the original methods encode only ASCII characters correctly.