Home > Back-end >  How to add a query parameter in isInUrl for isMatch
How to add a query parameter in isInUrl for isMatch

Time:02-04

I would like to match on a specific query parameter if it is in the URL. I pasted the query param directly into the isMatch but I don't think this is how to properly set it up:

isMatch: () => isInURL("search?q=", { usePathName: true }),

Do I have to structure the param differently? I assume so but I'm not familiar how since I am new to javascript.

CodePudding user response:

Your current implementation checks for a hardcoded string "search?q=" in the URL path name, which is not ideal if you want to match on different query parameters.

To match on a specific query parameter, you can extract the value of that parameter from the URL using JavaScript's URLSearchParams API. Here's an updated example:

isMatch: () => {
  const urlParams = new URLSearchParams(window.location.search);
  const paramValue = urlParams.get("q");
  return paramValue !== null;
},

In this example, window.location.search returns the query string of the current URL, which is then passed to URLSearchParams to extract the value of the "q" parameter. The function returns true if the parameter is present in the URL and false otherwise.

EDIT 1

You can check if the query parameter is attached to "search" in the URL by checking the pathname property of the window.location object, like this:

isMatch: () => {
  const urlParams = new URLSearchParams(window.location.search);
  const paramValue = urlParams.get("q");
  return paramValue !== null && window.location.pathname === "/search";
},
  • Related