0

I want to write a method that takes an array of strings and joins them with a + symbol, similarily to what Google does. This is my method:

function getQueryUrl(array) {
  let urlParamsString = array.join("+");
  const url = new URL(window.location);
  url.searchParams.set("query", urlParamsString);
  return url.toString();
}

But instead of getting the cleanly plus-separated URL, the URL API escapes the symbols with %2B. Is there any way to prevent this (apart from straight-up replacing the escaped symbols back to +)?

Selbi
  • 813
  • 7
  • 23
  • Does this answer your question? [URLSearchParams does not return the same string as found in a URL's parameters](https://stackoverflow.com/questions/45516070/urlsearchparams-does-not-return-the-same-string-as-found-in-a-urls-parameters) – Deniz Nov 23 '21 at 22:59
  • 3
    Wouldn't it be better understandable with examples? – Mister Jojo Nov 23 '21 at 23:00

2 Answers2

3

Update: use decodeURIComponent(url.toString());

kib gabriel
  • 108
  • 7
1

Try unescape() function:

function getQueryUrl(array) {
  let urlParamsString = array.join("+");
  const url = new URL(window.location);
  url.searchParams.set("query", urlParamsString);
  return unescape(url.toString());
}
Mana S
  • 509
  • 2
  • 6
  • 1
    The `unescape()` function is deprecated. We should use `decodeURI()` or `decodeURIComponent()` instead. (read: [JavaScript unescape()](https://www.w3schools.com/jsref/jsref_unescape.asp#:~:text=The%20unescape()%20function%20is,()%20or%20decodeURIComponent()%20instead.) ) – Akram Rabie Mar 22 '23 at 21:24