When to encode space to plus (+) or ?

前端 未结 5 1611
北恋
北恋 2020-11-22 02:12

Sometimes the spaces get URL encoded to the + sign, some other times to %20. What is the difference and why should this happen?

5条回答
  •  -上瘾入骨i
    2020-11-22 02:45

    + means a space only in application/x-www-form-urlencoded content, such as the query part of a URL:

    http://www.example.com/path/foo+bar/path?query+name=query+value
    

    In this URL, the parameter name is query name with a space and the value is query value with a space, but the folder name in the path is literally foo+bar, not foo bar.

    %20 is a valid way to encode a space in either of these contexts. So if you need to URL-encode a string for inclusion in part of a URL, it is always safe to replace spaces with %20 and pluses with %2B. This is what eg. encodeURIComponent() does in JavaScript. Unfortunately it's not what urlencode does in PHP (rawurlencode is safer).

    See Also HTML 4.01 Specification application/x-www-form-urlencoded

提交回复
热议问题