function that return value from url based on key in javascript

You can retrieve the value of the query string parameter from a URL using the URLSearchParams API in JavaScript. Here is a function that can return the value of a specified key from the query string of a given URL:

index.tsx
function getValueFromURL(url, key) {
  const searchParams = new URLSearchParams(new URL(url).search);
  return searchParams.get(key);
}
136 chars
5 lines

This function takes in the url and key as parameters. It creates a new URLSearchParams object with the search portion of the url. It then retrieves the value of the key parameter from the searchParams object using the get method.

Here's an example of how you can use this function to get the value of the id parameter from the current URL:

index.tsx
const currentURL = window.location.href;
const id = getValueFromURL(currentURL, 'id');
console.log(id);
104 chars
4 lines

In the above example, window.location.href returns the current URL, which is passed as the url parameter to getValueFromURL function along with the id key. The function returns the value of the id parameter, which is then logged in the console.

gistlibby LogSnag