Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save adinan-cenci/c4c40a9e9f79c97a2d908432be860c8d to your computer and use it in GitHub Desktop.
Save adinan-cenci/c4c40a9e9f79c97a2d908432be860c8d to your computer and use it in GitHub Desktop.
Get variables from the query string

Get query string variables

Lets say you have accessed an url on your site https://my-website.com/search?q=product-x&maxprice=300.
How can you get the variables search or maxprice in javascript ?

You can use this function:

function get(varName, alternative = null) 
{
    var url     = new URL(window.location.href);
    var params  = new URLSearchParams(url.search);
    
    return params.has(varName) ? 
        params.get(varName) : 
        alternative;
}

Then you can use it like this:

var searchFor = get('q');         // product-x
var maxPrice  = get('maxprice');  // 300
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment