JS urlencode


Javascript encodeURI() and encodeURIComponent() functions convert some special characters in a string to hexadecimal codes. The special characters include space, quotes < > etc.

var x="st john's";
var y=encodeURI(x);
alert(y); //st%20john's
var x="st john\"s";
var y=encodeURI(x);
alert(y); //st%20john%22s


Not all special characters will be converted, such as ; : , . * ' ? # @ & = + $ ~ - _ ( ) / ! will not be converted.

var x=";:,.*'?#@&=+$~-_()/!";
var y=encodeURI(x);
alert(y); //;:,.*'?#@&=+$~-_()/!


Unicode characters such as Chinese, Arabian, Japanese will be converted.

var x="نهر الأمزون";
var y=encodeURI(x);
alert(y); //%D9%86%D9%87%D8%B1%20%D8%A7%D9%84%D8%A3%D9%85%D8%B2%D9%88%D9%86
var x="北京";
var y=encodeURI(x);
document.write(y); //%E5%8C%97%E4%BA%AC


encodeURIComponent() has similar functions, except . * ' ~ - _ ! ( ) characters.

var x="st john's";
var y=encodeURIComponent(x);
alert(y); //st%20john's
var x=";:,.*'?#@&=+$~-_()/!";
var y=encodeURIComponent(x);
document.write(y); //%3B%3A%2C.*'%3F%23%40%26%3D%2B%24~-_()%2F!
var x="st john's";
document.write(encodeURIComponent(x));


decodeURIComponent() will convert the string back from encodeURIComponent().

var x="=test@example.com?";
var y=encodeURIComponent(x);
//document.write(y); //%3Dtest%40example.com%3F
var z=decodeURIComponent(y);
document.write(z); //=test@example.com?


decodeURI() will convert the string back from encodeURI().

var x="<st john's>";
var y=encodeURI(x);
document.write(y); //%3Cst%20john's%3E
var z=decodeURI(y);
alert(z); //<st john's>




endmemo.com © 2024  | Terms of Use | Privacy | Home