Javascript encodeURIComponent()

Introduction

The Javascript encodeURIComponent() function encodes a URI.

encodeURIComponent(str);
Parameters Meaning
str String. A component of a URI.

encodeURIComponent() escapes all characters except:

A-Z a-z 0-9 - _ . ! ~ * ' ( )

The following code shows the difference between encodeURI() and encodeURIComponent():

var set1 = ";,/?:@&=+$";  // Reserved Characters
var set2 = "-_.!~*'()";   // Unescaped Characters
var set3 = "#";           // Number Sign
var set4 = "ABC abc 123"; // Alphanumeric Characters + Space

console.log(encodeURI(set1));/*from   w  ww . j  a  va 2s .c o  m*/
console.log(encodeURI(set2));
console.log(encodeURI(set3));
console.log(encodeURI(set4));

console.log(encodeURIComponent(set1));
console.log(encodeURIComponent(set2));
console.log(encodeURIComponent(set3));
console.log(encodeURIComponent(set4));

Javascript encodeURIComponent() can encode URIs.

It replaces all invalid characters with a special UTF-8 encoding.

The encodeURIComponent() is designed to work solely on a segment of a URI.

encodeURIComponent() encodes every nonstandard character it finds.

let uri = "http:// www.java2s.com/illegal value.js#start";
console.log(encodeURI(uri));/*from  ww w .j a  v  a2 s .c  o  m*/
console.log(encodeURIComponent(uri));

The URI methods encodeURI(), encodeURIComponent(), decodeURI(), and decodeURIComponent() replace the escape() and unescape() methods, which are deprecated in the ECMA-262 third edition.




PreviousNext

Related