AndyJarrett

Escaping javscript URLs and their params

Did you know the escape() function is depreciated. As it turns out it doesn't handle its actual role of escaping characters that well i.e. non-ASCII. In its place you should be using encodeURI OR encodeURIComponent

encodeURI()

Use encodeURI when you want a working URL e.g. something you can use with location.href = '' as it assumes that the input is a complete URI that might have some characters which need encoding in it

var escapedURI = encodeURI("http://example.io/file name with spaces.html")  

If you looked at the value of escapedURI it would be

http://www.google.com/file%20name%20with%20spaces.html  

encodeURIComponent() encoded the complete string which seem handy but will actually destroy your URI

var encodeURIComponentWithSpaces = encodeURIComponent("http://example.io/file name with spaces.html")  

Check out this URL

http%3A%2F%2Fexample.io%2Ffile%20name%20with%20spaces.html  

encodeURIComponent() should be used when encoding a param part of a URI.

var encodeURIComponentOnParamsOnly = "http://example.io/file.html?para1=" + encodeURIComponent("va1!%$");  

This would return

http://example.io/file.html?para1=va1!%25%24