Encoding URI

To encode URLs, use encodeURI() or encodeURIComponent(). To decode them, use decodeURI() or decodeURIComponent().

Note that encodeURIComponent does not escape the ' character. A common bug is to use it to create HTML attributes such as href='MyUrl', which could suffer an injection bug. If you are constructing HTML from strings, either use " instead of ' for attribute quotes, or add an extra layer of encoding (' can be encoded as %27).
// 1. Use encodeURI when you want a working URL.
console.log(encodeURI("http://www.google.com/a file with spaces.html"));

// 2. Use encodeURIComponent when you want to encode
// a URL parameter.
var param1 = encodeURIComponent("http://example.com/?a=12&b=55");
url = "http://domain.com/?param1=" + param1 + "&param2=99";
console.log(url);

console.log(decodeURIComponent(url));

http://www.google.com/a%20file%20with%20spaces.html http://domain.com/?param1=http%3A%2F%2Fexample.com%2F%3Fa%3D12%26b%3D55&param2=99 http://domain.com/?param1=http://example.com/?a=12&b=55&param2=99