I need to set a number of URL parameters, which also need to include a special character $
Currently I am using .set()
to create and set these parameter values:
const myUrl = new URL("http://www.example.com/?");
let params = new URLSearchParams();
params.set('$param1', '60');
params.set('$param2', '100');
I understand that I need to use encodeURI()
to ensure that I get $
in the URL and not %24
– but at what stage do I do this?
If I do this when I stringify and add the params to the URL they have already been converted.
myUrl.search = encodeURI(params.toString());
// Outputs: http://www.example.com/?%24param1=60&%24param2=100
// Desired: http://www.example.com/?$param1=60&$param2=100
2
Answers
Since you need it and your server supports it, just fix it at the end
In your case, the
$
character is being encoded as%24
because it’s a reserved character in URLs. TheURLSearchParams
object’sset
method automatically encodes these characters to ensure the resulting string is a valid URL.However, if you want to include the
$
character as is, you can bypass the automatic encoding by manually constructing the query string:This will give you the desired output, but be aware that this might not be a valid URL according to the URL specification, as
$
is a reserved character. This could potentially lead to issues with some servers or APIs.If you control the server or API you’re interacting with and you’re sure it can handle URLs with
$
characters in the query string, then this approach should work. Otherwise, it’s generally safer to stick with the automatic encoding provided byURLSearchParams
.Please confirm if this solution works for you or if you need further assistance.