I need to set some URL parameters, which also need to contain a special character $
Currently I am using .set()
to create and set the values of these parameters:
const myUrl = new URL("http://www.example.com/?"); let params = new URLSearchParams(); params.set('$param1', '60'); params.set('$param2', '100');
I know I need to use encodeURI()
to make sure I get $
in the URL and not $
- But at what stage should I do this?
If I do something like this when converting the parameters to strings and adding them to the URL, they are already converted.
myUrl.search = encodeURI(params.toString()); // Output: http://www.example.com/?$param1=60&$param2=100 // Expectation: http://www.example.com/?$param1=60&$param2=100
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.