tags:

views:

1131

answers:

4

Why does the javascript function encodeURIComponent encode spaces to the hex unicode value %20 insteady of +. Should uri parameters not spaces to +?

+3  A: 

Spaces encode to %20, I believe that's their ASCII character code.

However, developers have taken a shine to encoding spaces to + because it generates URLs that are readable and typeable by human beings.

Jeremiah Peschka
A: 

As a general rule, file paths should have spaces encoded as %20. Query string parameters should have spaces encoded as +.

For example: http://www.example.com/a%20file.ext?name=John+Doe

R. Bemrose
+2  A: 

The + is not recognised as a space in all uses of a URI for example try using this link:-

mailto:bloke@somewhere?subject=Hello+World

The subject line still has the + whereas:-

mailto:bloke@somewhere?subject=Hello%20World

works.

AnthonyWJones
A: 

Using the + sign as a space is for historical reasons. The CGI back then enabled web-servers to use normal command line programs as "web applications". Within the scripting-world of command line programs most interpreters/shell-languages had space separated lists of values like

items = (A beautiful world)
foreach( item in $items ) echo "* $item"

Call such a "list render application" from command line:

render-list A beautiful world

Call the same "list render application" over http and a webserver:

http://testhost/cgi-bin/render-list?A+beautiful+world

For the most use-cases the meaning of the + sign would be kind of an item- or term-separator in the value of an parameter. And that is exacly the area where i recommend using it today.