Encode special characters when setting URL parameters
P粉348915572
2023-08-17 11:25:49
<p>I need to set some URL parameters, which also need to contain a special character <code>$</code></p>
<p>Currently I am using <code>.set()</code> to create and set the values of these parameters: </p>
<pre class="brush:php;toolbar:false;">const myUrl = new URL("http://www.example.com/?");
let params = new URLSearchParams();
params.set('$param1', '60');
params.set('$param2', '100');</pre>
<p>I know I need to use <code>encodeURI()</code> to make sure I get <code>$</code> in the URL and not <code>$</code> - But at what stage should I do this? </p>
<p>If I do something like this when converting the parameters to strings and adding them to the URL, they are already converted. </p>
<pre class="brush:php;toolbar:false;">myUrl.search = encodeURI(params.toString());
// Output: http://www.example.com/?$param1=60&$param2=100
// Expectation: http://www.example.com/?$param1=60&$param2=100</pre>
<p><br /></p>
Since you need it and your server supports it, just fix it at the end
In your case, the
$
character is encoded as$
because it is a reserved character in URLs. Theset
method of theURLSearchParams
object will automatically encode these characters to ensure that the generated string is a valid URL.However, if you want to include the
$
characters as-is, you can bypass the automatic encoding by manually building the query string:This will give you the desired output, but please note that this may not be a valid URL according to URL specifications, as
$
is a reserved character. This may cause problems with certain servers or APIs.If you control the server or API you are interacting with, and you are confident that it can handle URLs with
$
characters in the query string, this method should work. Otherwise, it's usually safest to use the automatic encoding provided byURLSearchParams
.Please confirm if this solution works for you, or if you need further assistance.