DEV Community

Cover image for Fetch query data from URL using javascript
Rajnish Katharotiya
Rajnish Katharotiya

Posted on

Fetch query data from URL using javascript

Photo by Tim van der Kuip on Unsplash

Have you ever used the URL's query parameter into a page? I'm sure most of us did, share me in a comment how'd you done it.

Before going ahead, I would like to welcome you to a new episode of series call Javascript Useful Snippets. In this series, I'm sharing some shortcodes and useful functions that can let you make your code faster and neat. So, if you haven't read my previous episodes articles please check it out here or else stay tuned till the end to learn something new 😋 .

Getting query parameters from URL is not a hard job but if you are writing it all again-n-again then it's bad practice. So in solution, I defined one global function into an app called getUrlParams(). This function takes URL and in output, returns object with key-value pair of parameters ( data of URL ) if any consist into URL else returns an empty object.

What is inside getUrlParams() ?

const getUrlParams = url => {
  const paramsData = url.match(/([^?=&]+)(=([^&]*))/g) || []        // [ "key=value", "key2=value2"]

  return paramsData.reduce(
    (a, v) => ((a[v.slice(0, v.indexOf('='))] = v.slice(v.indexOf('=') + 1)), a),
    {}
  );
}

In function first, I used regex (/([^?=&]+)(=([^&]*))/g) to get an array of data with match() method of string ( this method will create a collection of records which match with given string - in our case, it's the regex for key=value formatted data) and stored into one constant with fallback value as [].

Next, By using the reduced method on an extracted collection of data I've created an object with key-value pair. To do that, inside of reduce I'm first finding an index of "=" into each record and from 0 to founded index string; I stored it as key, and after the founded index data; I stored it as the value of that key. In last just returned the whole function's output as a result of this function.

How to use getUrlParams() ?

getUrlParams('http://dev.to/page?name=Rajnish&surname=Katharotiya'); // {name: 'Rajnish', surname: 'Katharotiya'}
getUrlParams('dev.to'); // {}

As you have seen, with the first URL input it's returning an object with key-value pair of provided data into the path whereas the next given empty object because location path doesn't have any params present in it.

This function becomes very useful for me wherever I need to extract data from URL just pass it to this and in return, I'll get the organized object without hurdle 😀. So, I thought to share it with you guys too. I hope you liked my explanation ( if yes, please hit like ❤️ button ) and if you learned something new or found informative then hit the follow button too from here to stay updated with me as I'm learning & sharing every day something useful. 😋

Also follow/subscribe me on my social media account to connect with me : twitter, youtube

Top comments (5)

Collapse
 
bytebodger profile image
Adam Nathaniel Davis • Edited

As noted by a previous commenter, you don't have to manually extract this with a RegEx. The following is what I use:

export default function getUrlParameters() {
   const urlParams = new URLSearchParams(window.location.search);
   let processedUrlParams = {};
   for (let entry of urlParams.entries()) {
      let [key, value] = entry;
      if (value.toLowerCase() === 'true')
         value = true;
      else if (value.toLowerCase() === 'false')
         value = false;
      else if (value.toLowerCase() === 'null')
         value = null;
      else if (!isNaN(parseFloat(value)))
         value = parseFloat(value);
      processedUrlParams[key] = value;
   }
   return processedUrlParams;
};

You could just use urlParams.entries() and be done with it. But I added extra processing so that, if other data types can be inferred (Boolean, null, numeric) from the data they'll be returned as their proper data type.

Collapse
 
rajnishkatharotiya profile image
Rajnish Katharotiya

Thanks, great solution. Found something new 👏🏻👍

Collapse
 
joeattardi profile image
Joe Attardi

Why not just use the built-in URL object? See developer.mozilla.org/en-US/docs/W...

Collapse
 
rajnishkatharotiya profile image
Rajnish Katharotiya

Yes surely we can use this too, found new way thanks 👏🏻👏🏻

Collapse
 
sharadcodes profile image
Sharad Raj (He/Him)

Agree