Which of these two methods should be used for encoding URLs?
URL encoding replaces unsafe ASCII characters with a "%" followed by two hexadecimal digits. URLs cannot contain spaces. URL encoding normally replaces a space with a plus (+) sign or with %20.
The encodeURIComponent function is used to encodes a Uniform Resource Identifier (URI) component by replacing each instance of certain characters by one, two or three escape sequences representing the UTF-8 encoding of the character.
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);
If you're encoding a string to put in a URL component (a querystring parameter), you should call encodeURIComponent
.
If you're encoding an existing URL, call encodeURI
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With