Efficiently Retrieve URL Parameters in JavaScript: A One-Liner Function for Easy Access by Name

Efficiently Retrieve URL Parameters in JavaScript: A One-Liner Function for Easy Access by Name

·

1 min read

Table of contents

No heading

No headings in the article.

Here's a one-liner function in JavaScript to get a specific URL parameter by name:

const getUrlParameter = (name) => new URLSearchParams(window.location.search).get(name);

You can call this function and pass the parameter name as a string:

const myParam = getUrlParameter('myParam');

Then console.log(myParam); to see the output.

This function uses the URLSearchParams API to parse the query string in the URL and returns the value of the parameter with the specified name. If the parameter doesn't exist in the URL, it returns null.