Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use encodeURI or encodeURIComponent for encoding URLs?

Tags:

javascript

Which of these two methods should be used for encoding URLs?

like image 942
Aditya Shukla Avatar asked Dec 27 '10 18:12

Aditya Shukla


People also ask

What is the best way to URL encode a string?

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.

What is encodeURIComponent used for?

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.


2 Answers

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); 
like image 181
Quentin Avatar answered Sep 22 '22 13:09

Quentin


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.

like image 21
SLaks Avatar answered Sep 22 '22 13:09

SLaks