WebMasterCampus
WEB DEVELOPER Resources

Javascript How to Encode Url

Learn How to Encode Url in Javascript


Javascript Encode Url

Javascript provide built-in functions to accomplish URL encoding. Following are the functions we can use.

If you want to pass a URL into a GET parameter of other page, It’s recommended to use encodeURIComponent.

encodeURI Function

The encodeURI() function does not encode characters that have special meaning (reserved characters) for a URI.

encodeURI() escapes all characters except following:

    A-Z a-z 0-9 ; , / ? : @ & = + $ - _ . ! ~ * ' ( ) #

Example of encodeURI

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

console.log(encodeURI(set1)); // ;,/?:@&=+$#
console.log(encodeURI(set2)); // -_.!~*'()
console.log(encodeURI(set3)); // ABC%20abc%20123 (the space gets encoded as %20)

encodeURIComponent Function

var myOtherUrl =  "http://www.google.com/index.html?url=" + encodeURIComponent(paameters);

encodeURIComponent() escapes all characters except following:

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

Example of encodeURIComponent

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

console.log(encodeURIComponent(set1)); // %3B%2C%2F%3F%3A%40%26%3D%2B%24%23
console.log(encodeURIComponent(set2)); // -_.!~*'()
console.log(encodeURIComponent(set3)); // ABC%20abc%20123 (the space gets encoded as %20)

Learn more about encodeURIComponent

Learn more about encodeURI

Created with love and passion.