The query string portion of a URL (also called the "search string") assigns values to specific parameters. These typically are added to the end of a URL beginning with a question mark ("?").

How do you extract the URL query string for a web page when coding in JavaScript?

JavaScript has a built-in way to get this information using the Location API interface, which represents the location (URL) of the current web page you're located on. The global Window interface has access to the Location object that can be used via window.location.

Using that interface, you can get the URL origin with this method:

    
      window.location.search
    
  

This method will return a USVString containing a "?" symbol followed by the parameters of the current page's URL.

If the URL doesn't have any query string values, an empty string ("") will be returned.

Here are some example returned values to expect:

    
      // Page URL: https://coderrocketfuel.com?q=articles
      window.location.search == "?q=articles"

      // Page URL: https://coderrocketfuel.com
      window.location.search == ""
    
  

To quickly test this, open the developer tools in your favorite browser and execute the window.location.search method in the JavaScript console. If the page contains query string values, those values will be logged to the console.

For more information on the browser support for this method, see its MDN web docs page.

If you need to parse out individual parameters from the query string, JavaScript also provides a URL.searchParams method that makes doing that easy.

The searchParams method takes a given URL and returns an object with each parameter value in it.

Here's how you'd use it in your code:

    
      // Page URL: https://coderrocketfuel.com/?query1=123&query2=789
      let params = (new URL(window.location.href)).searchParams

      let query1 = params.get("query1") // returns "123"
      let query2 = params.get("query2") // returns "789"
    
  

Let's quickly go over each part of that code snippet.

First, we create a new URL object using the current URL of the page (window.location.href) and store it in a params variable.

Using that params variable, we can use the get() method to retrieve both query string parameters.

For more information on the browser support for this method, see its MDN web docs page.

Thanks for reading and happy coding!