URL Parameters as Object

JavaScriptJavaScriptBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will explore how to extract and map URL parameters into a JavaScript object using regular expressions and array methods. We will learn how to use String.prototype.match() to obtain all key-value pairs and Array.prototype.reduce() to transform them into a single object. By the end of this lab, you will have a better understanding of how to work with URLs and extract useful information from them.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript(("`JavaScript`")) -.-> javascript/AdvancedConceptsGroup(["`Advanced Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") javascript/AdvancedConceptsGroup -.-> javascript/higher_funcs("`Higher-Order Functions`") subgraph Lab Skills javascript/variables -.-> lab-28364{{"`URL Parameters as Object`"}} javascript/data_types -.-> lab-28364{{"`URL Parameters as Object`"}} javascript/arith_ops -.-> lab-28364{{"`URL Parameters as Object`"}} javascript/comp_ops -.-> lab-28364{{"`URL Parameters as Object`"}} javascript/higher_funcs -.-> lab-28364{{"`URL Parameters as Object`"}} end

Object with URL Parameters

To create an object that contains the parameters of the current URL, follow these steps:

  1. Open the Terminal/SSH and type node to start practicing coding.
  2. Use String.prototype.match() with an appropriate regular expression to extract all the key-value pairs.
  3. Use Array.prototype.reduce() to map and combine them into a single object.
  4. Pass location.search as the argument to apply to the current URL.

Here is the code:

const getURLParameters = (url) =>
  (url.match(/([^?=&]+)(=([^&]*))/g) || []).reduce(
    (a, v) => (
      (a[v.slice(0, v.indexOf("="))] = v.slice(v.indexOf("=") + 1)), a
    ),
    {}
  );

You can use this function with any URL to get an object with its parameters. Here are some examples:

getURLParameters("google.com"); // {}
getURLParameters("http://url.com/page?name=Adam&surname=Smith");
// {name: 'Adam', surname: 'Smith'}

Summary

Congratulations! You have completed the URL Parameters as Object lab. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like