Should I use encodeURI or encodeURIComponent for encoding URLs?

It depends on what you are actually wanting to do.

encodeURI assumes that the input is a complete URI that might have some characters which need encoding in it.

encodeURIComponent will encode everything with special meaning, so you use it for components of URIs such as

var world = "A string with symbols & characters that have special meaning?";
var uri = 'http://example.com/foo?hello=' + encodeURIComponent(world);

Leave a Comment