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.tsx136 chars5 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.tsx104 chars4 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