Pulling Query Params from URL in Javascript
Wednesday, June 24th, 2015As part of this continuing project at The Shop, one of the things we're going to need is to be able to put URLs in emails and have the user click on them, and have it take them right to the document in question. This means we need to have the index.html page accept a query param of the ID of the thing to load. Then, if we get to the page, and this query param is there, then we load the requested data, if not, we put up a blank page, and then let the user search for the document they want.
Seems simple. If we can get the query params from the URL in Javascript.
Thankfully, someone posted this lovely little function:
/* * This function extracts the provided query string from the URL for * the page we're on, and it's a nice and simple way to get the parts * of the URL that we're looking to see if they provided. */ function qs(key) { // escape RegEx meta chars key = key.replace(/[*+?^$.\[\]{}()|\\\/]/g, "\\$&"); var match = location.search.match(new RegExp("[?&]"+key+"=([^&]+)(&|$)")); return match && decodeURIComponent(match[1].replace(/\+/g, " ")); }
Then we can have a little script block at the bottom of the index.html page, after loading all the javascript libraries, that checks to see if this parameter is being provided:
// when the page is done loading, then load up the form var lid = qs('loan'); $( document ).ready(loadLoan(($.isNumeric(lid) ? lid : null)));
This snip does everything we want - checks for the numeric value, and if it's there, uses it, if not, shows the blank page. Very nice.