最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to remove one specific query parameter from URL in Next.js? - Stack Overflow

programmeradmin8浏览0评论

http://localhost:3000/?search=test&type=abc&category=xyz

After I search for test (among with type and category), the URL changes to the URL above.

return router.push(
      {
         pathname: `/`,
         query: {
             // something to do here...
         },
      },
      "",
      { scroll: false }
);

Next, I have an onClick with this router.push.

I would like to remove ONLY the search query and keep the type and category queries. How is it possible? The documentation doesn't mention anything about this.

http://localhost:3000/?search=test&type=abc&category=xyz

After I search for test (among with type and category), the URL changes to the URL above.

return router.push(
      {
         pathname: `/`,
         query: {
             // something to do here...
         },
      },
      "",
      { scroll: false }
);

Next, I have an onClick with this router.push.

I would like to remove ONLY the search query and keep the type and category queries. How is it possible? The documentation doesn't mention anything about this.

Share Improve this question edited May 11, 2022 at 20:09 juliomalves 50.3k23 gold badges177 silver badges168 bronze badges asked May 10, 2022 at 10:46 DavidDavid 3411 gold badge10 silver badges27 bronze badges
Add a comment  | 

4 Answers 4

Reset to default 8

To remove the query param completely from the url:

const { paramToRemove, ...routerQuery } = router.query;
router.replace({
  query: { ...routerQuery },
});

You can call router.push with the current query string, but omitting the search parameter.

const params = new URLSearchParams(router.query);
params.delete('search');
const queryString = params.toString();
const path = `/${queryString ? `?${queryString}` : ''}`;

router.push(path, '', { scroll: false });

Given that you're currently at /?search=test&type=abc&category=xyz, the above will route you to /?type=abc&category=xyz. This will also handle scenarios where the type and category query parameters aren't present.

You can just remove it by deleting the property in router.query

delete router.query.search;
router.push(router);

let queries = Object.assign({}, router.query);

delete queries.search;
return router.push(
      {
         pathname: `/`,
         query: queries
      },
      "",
      { scroll: false }
);
发布评论

评论列表(0)

  1. 暂无评论