Encode special characters when setting URL parameters
P粉348915572
P粉348915572 2023-08-17 11:25:49
0
2
394

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


P粉348915572
P粉348915572

reply all (2)
P粉147747637

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粉986028039

    In your case, the$character is encoded as$because it is a reserved character in URLs. Thesetmethod of theURLSearchParamsobject 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 byURLSearchParams.

    Please confirm if this solution works for you, or if you need further assistance.

      Latest Downloads
      More>
      Web Effects
      Website Source Code
      Website Materials
      Front End Template
      About us Disclaimer Sitemap
      php.cn:Public welfare online PHP training,Help PHP learners grow quickly!