search

Home  >  Q&A  >  body text

Encode special characters when setting URL parameters

<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>
P粉348915572P粉348915572483 days ago460

reply all(2)I'll reply

  • P粉147747637

    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,"$"))

    reply
    0
  • P粉986028039

    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.

    reply
    0
  • Cancelreply