/  Technology   /  Get URL Parameters in JavaScript
url

Get URL Parameters in JavaScript

 

Methods involved to get URL parameters

How do you create a String URL?

String containing this text to create a URL object:

  URL myURL = new URL("www.air.irctc.co.in /");
  • The URL object created above represents an absolute URL.
  • An absolute URL contains all of the necessary information to reach the resource.

url.searchParams.get

If the URL of your page is https:// www.air.irctc.co.in /?name=Jonathan%20Smith& type =18

We can extract the name and type parameters using url.searchParams.get method

let params = (new URL(document.location)).searchParams;
            var name = url.searchParams.get("name");
            var type = url.searchParams.get("type");

By using above mentioned methods we can extract URL parameters using JavaScript.

JavaScript Code:

<!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title> Get URL parameters</title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="Goto Previous page/styles.css">
    </head>
    <body text-align:'center'>
        <script>
            var str = "https://www.air.irctc.co.in/onewaytrip?&type=reservation&name=originCountry&origin=HYD&originCity=Hyderabad&originCountry=IN&destination=DEL&destinationCity=New%20Delhi&destinationCountry=IN&flight_depart_date=2022-09-28&ADT=1&CHD=0&INF=0&class=Economy&airlines=&ltc=0&searchtype=&isDefence=true&bookingCategory=0&eType=0";
            var url = new URL(str);
            var name = url.searchParams.get("name");
            var type = url.searchParams.get("type");
            console.log(name);
            console.log(type);
            alert(name);
            alert(type);
            document.write("Params Name is : ",name +" <br> Params Type is : ",type);
        </script>
    </body>
    </html>

Output:

This alert box page says params name extracted from url.searchParams.get(“name”) method.

i2

This alert box page says params type extracted from url.searchParams.get(“type”) method.

Get URL Parameters in JavaScript

Get URL Parameters in JavaScript

Given URL

https://www.air.irctc.co.in/onewaytrip?&type=reservation&name=originCountry&origin=HYD&originCity=Hyderabad&originCountry=IN&destination=DEL&destinationCity=New%20Delhi&destinationCountry=IN&flight_depart_date=2022-09-28&ADT=1&CHD=0&INF=0&class=Economy&airlines=&ltc=0&searchtype=&isDefence=true&bookingCategory=0&eType=0";

From the above URL we extracted name and type parameters, these two parameters are URL Parameters.

 

Leave a comment