简体   繁体   中英

Encoding spaces with the javascript encodeURIComponent function

Why does the JavaScript function encodeURIComponent encode spaces to the hex Unicode value %20 instead of + . Should URI parameters not spaces to + ?

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.

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM