How to Encode Spaces in URLs
Part of the Encoding Toolkit%20or + specifically inside a query string
Explanation
A space is never valid literally inside a URL — %20 is the correct, universal way to represent one, and it works in every part of a URL: the path, the query string, and the fragment.
Query strings have one additional option: a literal + also means a space there, following the older application/x-www-form-urlencoded convention that URLSearchParams and most server frameworks still use. This only applies inside a query string — a + in a path segment means a literal plus sign, not a space, which is exactly why mixing the two up is such a common bug.
See URL Encoding Explained for the full mechanism behind both forms, or How to Encode Special Characters in URLs for a quick-reference table covering more than just spaces.
Valid examples
/files/my%20file.txtA space in a path segment — always %20, never +.
?q=hello%20worldA space in a query value — %20 always works here too.
?q=hello+worldA space in a query value using the form-encoding convention — decodes the same as %20, but only inside a query string.
#section%20oneA space in a fragment — %20, the same as a path segment.
Invalid examples
/files/my file.txtAn unencoded literal space — invalid to construct programmatically, even though some browsers silently fix it on navigation.
/files/my+file.txtUsing + in a path segment — decodes to a literal plus sign, not a space. The +-for-space rule is query-string only.
/files/my_file.txtSubstituting an underscore or hyphen instead of encoding — changes the actual value rather than representing the original space.
?q=hello%2520worldDouble-encoding — the % itself got encoded a second time, producing %2520 instead of %20.