params

Before heading out to what this post is going to be about, let me just give you one easy example of each type of URL.

Here is the path string param example:

http://localhost:3000/auth/resetpassword/5dc5e02767b0f815e448e073/2e27e113fc3169d3a70d7d31330a7cc31ded18e6

Here is the same URL written in query string:

http://localhost:3000/auth/resetpassword?userid=5dc5e02767b0f815e448e073&resettoken=2e27e113fc3169d3a70d7d31330a7cc31ded18e6

Now the best part of these two when combined with JavaScript is that you can get each part individually. What I mean by ‘part’ is that each URL is constructed with the following ‘parts’:

protocol://host.com/pathname/pathname.html/search

That same URL with our example is built as follow:

  • protocol: http/s
  • host: localhost:PORT or any URL, example: google.com
  • pathname: auth/resetpassword
  • search: :userid/:resettoken

Now that you have an idea on how URLs are built, let’s break them apart.

Breaking an URL built on PATH:

const url = window.location.pathname.split('/');
const userid = url[0];
const token = url[1];
console.log({ userid, token});

By starting and splitting the pathname with slashes(/) we can get our values individually with no problem at all ONLY AFTER the main URL(auth/resetpassword).

Breaking an URL built on QUERY:

const url = window.location.search;
const params = new URLSearchParams(url);
const userid = params.get('userid');
const token = params.get('resettoken');
console.log({userid, resettoken: token});

Using window.location.search will fetch everything after the ? operator found on any URL.

That is it, feel free to share this article if you found it useful. Bye-Bye 🙂 .

Leave a Reply

Back to Top