Javascript / jQuery encode a URL
1 min read

Javascript / jQuery encode a URL

Javascript has a built in function encodeURIComponent(str) and encodeURI(str) to encode strings into url.

encodeURI()

This function encodes special characters, except: , / ? : @ & = + $ #

var url = "1234 fake street";
url = encodeURI(url);
alert(url); // this prints out "1234%20fake%20street"

encodeURIComponent(str)

This function encodes special characters. In addition, it encodes the following characters: , / ? : @ & = + $ #

var url ="san jose, ca";
url = encodeURIComponent(url);
alert(url); // this prints out "san%20jose%C%20ca"