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


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(" name with spaces.html")  

If you looked at the value of escapedURI it would be  

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

var encodeURIComponentWithSpaces = encodeURIComponent(" name with spaces.html")  

Check out this URL  

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

var encodeURIComponentOnParamsOnly = "" + encodeURIComponent("va1!%$");  

This would return!%25%24  

comments powered by Disqus