P粉1477476372023-08-18 09:43:27
Since you need it and your server supports it, just fix it at the end
const myUrl = new URL("http://www.example.com/?"); let params = myUrl.searchParams; params.set('$param1', '60'); params.set('$param2', '100'); console.log(myUrl.toString().replace(/%24/g,"$"))
P粉9860280392023-08-18 09:07:27
In your case, the $
character is encoded as $
because it is a reserved character in URLs. The set
method of the URLSearchParams
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:
const myUrl = new URL("http://www.example.com/?"); let params = ['$param1=60', '$param2=100'].join('&'); myUrl.search = params; console.log(myUrl.toString()); // 输出:http://www.example.com/?$param1=60&$param2=100
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 by URLSearchParams
.
Please confirm if this solution works for you, or if you need further assistance.