GET URL Parameters Using JavaScript - Web Development

     

    What are URL parameters ? Let's say one URL of a site is like -

 https://www.example.com/users?name=John&id=23

In this URL we can see that some parameters are passed as arguments at the end like (name=John and id=23). This means that this particular URL is trying to do something with John of id 23. Now, let's say you are the host of this site. How can you GET these parameter values which are being opened by a user. To make it simple, suppose your website provides data for some names with ids. The data which you will show in your website depends on this parameters provided on the URL. Today, we will learn how to fetch them using JavaScript

    Let's fix a goal that whatever parameters of name and id value are in the URL we are to print them on the webpage. In this case, we will print John and 23 on the webpage. So, let's begin. 

  

    In JavaScript, window.location returns the URL of the location bar. We will create an URLSearchParams() object from which we will get our parameters. From this object we can GET our needs( id and name in this case ). For ease we will create a function for getting parameter value(23, John) according to parameter names(id, name). And then, we will print them in webpage. Enough explanation , see the code Now. To be noted that if no parameters are there in URL then values will be null that's why we checked the condition in if.

<script>
 function getUrlParams(urlParams) {
        let urlParamObject = new URLSearchParams(window.location.search);
        return urlParamObject.get(urlParams);
      }

      let idValue = getUrlParams("id");
      let nameValue = getUrlParams("name");

      if (idValue != null && nameValue != null) {
        let body = document.querySelector("body");

        body.innerHTML = `<h2>${idValue}</h2><h4>${nameValue}</h4>`;
      }
</script> 

Hope, I am able to explain the concept properly. If any doubt or opinion or suggestion comes up in your mind let me know in the comment section. Also if you need any code you can ask me in the comments below. Finally, do mention your country in the comment section . That will really encourage me. Thank you . Have a nice day....✌✌

Imon Raj

Software, Web & Android Developer

My Skills:

Comments

Post a Comment

Popular posts from this blog

Which one is better ? GeeksForGeeks or Leetcode ? How many questions to solve ?

Random jokes generator using API (Free)