How to Get URL Parameter in jQuery

Shraddha Paghdar Feb 02, 2024
How to Get URL Parameter in jQuery

In today’s post, we’ll learn how to get URL parameters in jQuery.

Get URL Parameters in jQuery

In JavaScript, the Search property of the Location interface is a search string, also known as a query string; that is, a string containing a ? followed by the URL parameters.

Modern browsers have URLSearchParams and URL.SearchParams to make it less difficult to parse question string parameters. The get() technique of the URLSearchParams interface returns the primary value associated with the specified search parameter.

Syntax:

get(name)

Let’s understand it with the following simple example.

let dummyURL =
    'https://delftstack.com/howto/jquery/?technology=jquery&post=urlParameter'
const extractURLParameter = (searchParam) => {
  const searchPageURL = dummyURL.split('?')[1];
  const searchURLVariables = searchPageURL.split('&');
  let searchParameterName;

  for (let i = 0; i < searchURLVariables.length; i++) {
    searchParameterName = searchURLVariables[i].split('=');

    if (searchParameterName[0] === searchParam) {
      return searchParameterName[1] === undefined ?
          true :
          decodeURIComponent(searchParameterName[1]);
    }
  }
  return false;
};


console.log(extractURLParameter('technology'));
console.log(extractURLParameter('post'));

const params =
    new URLSearchParams(window.location.search);  // pass the dummyURL here
const name = params.get('editor_console');
console.log(name)

In the example above, we defined a general function that extracts the URL parameter from the current location URL. The location interface search properties extract the parameters from the URL and the value separated by ?.

The next step is to split the parameters with &. Now we can iterate through each of the parameters and check whether the requested parameter exists or not.

We can separate the parameter and the key by =.

The second alternative is to use the URLSearchParams interface directly, which provides the list of all query parameters. The Get method extracts the value associated with the requested parameter.

This is an efficient solution if the browser supports URLSearchParams.

Try running the code snippet above in any browser that supports jQuery. The following result is displayed.

jquery
urlParameter

Demo

Shraddha Paghdar avatar Shraddha Paghdar avatar

Shraddha is a JavaScript nerd that utilises it for everything from experimenting to assisting individuals and businesses with day-to-day operations and business growth. She is a writer, chef, and computer programmer. As a senior MEAN/MERN stack developer and project manager with more than 4 years of experience in this sector, she now handles multiple projects. She has been producing technical writing for at least a year and a half. She enjoys coming up with fresh, innovative ideas.

LinkedIn