skip to Main Content

I need to generate the following
deviceSearch?q=4100&origin=pdp

instead I am seeing
deviceSearch?q=4100%26origin%3Dpdp

Googling this problem it seems I cannot do this.
I tried the following that did not work

    url.searchParams.set('q', item.selectionText);
    url.searchParams.append(name: origin, value: pdp);

I tried joining the text which did not work.

url.searchParams.set('q', item.selectionText.concat('&origin=pdp'));

I also tried using escape code ” before those characters. I assume I am missing something in addition to any real knowledge of javascript.

2

Answers


  1. You can just call set again, same way you are setting the q parameter. & symbol is added by the URLSeachParams class itself.

    url.searchParams.set('q', item.selectionText);
    url.searchParams.set('origin', 'pdp');
    

    You can also use .append, the syntax would be the same:

    url.searchParams.append('origin', 'pdp');
    

    But that might not be what you’re trying to do. Difference is that set will override the value if you try set the same parameter twice, and append will let add the same parameter multiple times.

    url.searchParams.set('foo', '1');
    url.searchParams.set('foo', '2');
    // results in '?foo=2
    
    url.searchParams.append('foo', '1');
    url.searchParams.append('foo', '2');
    // results in ?foo=1&foo=2
    
    Login or Signup to reply.
  2. Each of these are separate query parameters of the URL string. You don’t manually add the & or = symbols as they are a result of the parameter definitions. The url.searchParams.set takes the parameter name as the first argument and the value assigned as the second argument. That creates the key value pair or (parameter=value) The & is a result of more than one parameter being set with that method.

    If you called this method 4 different times you would have this example URL string.

    url.searchParams.set('q', '4100');
    url.searchParams.set('origin', 'php');
    url.searchParams.set('name', 'test');
    url.searchParams.set('age', 12);
    

    // /deviceSearch?q=4100&origin=php&name=test&age=12

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