skip to Main Content

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


  1. 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,"$"))
    Login or Signup to reply.
  2. In your case, the $ character is being encoded as %24 because it’s a reserved character in URLs. The URLSearchParams object’s set 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:

    const myUrl = new URL("http://www.example.com/?");
    
    let params = ['$param1=60', '$param2=100'].join('&');
    
    myUrl.search = params;
    
    console.log(myUrl.toString());
    // Outputs: http://www.example.com/?$param1=60&$param2=100
    

    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 by URLSearchParams.

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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search