Selbi
Selbi

Reputation: 833

Prevent URL.toString() from escaping plus (+) symbols

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 +)?

Upvotes: 0

Views: 1481

Answers (2)

kib gabriel
kib gabriel

Reputation: 138

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

Upvotes: 5

Mana S
Mana S

Reputation: 519

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());
}

Upvotes: 1

Related Questions