0

Hi I have an array of a query string with the same key and I wanna remove one of them:

https://example.com/something?orderby=date&orderby=price&orderby=amount

  const [searchParams, setSearchParams] = useSearchParams();
  let udpatedSearchParams = new URLSearchParams(searchParams.toString());

  const remove = (key) => {
    udpatedSearchParams.delete(key);
    setSearchParams(udpatedSearchParams.toString());
  };

remove("orderby") // => https://example.com/something?

but I wanna this:

remove("orderby","amount") // => https://example.com/something?orderby=date&orderby=price

1 Answer 1

1

It doesn't have the fanciest variable naming but it does the work

const remove = (key, url) => {
  let reqUrl = url.split("?");
  let paramArray = reqUrl[1].split("&");
  let result = paramArray.reduce(function (a, b) {
    console.log(b);
    if (b.split("=")[1] !== key) {
      return [...a, b];
    } else {
      return [...a];
    }
  }, []);

  return reqUrl[0] + "?" + result.join("&");
};

remove(
  "price",
  "https://example.com/something?orderby=date&orderby=price&orderby=amount"
);

output will be:

'https://example.com/something?orderby=date&orderby=amount'
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! and how to set it as a query string ?
Function returns the query string as result.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.