Home > Back-end >  remove specific query string react-router-dom v6
remove specific query string react-router-dom v6

Time:07-09

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

CodePudding user response:

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'
  • Related