How to parse URL using JavaScript ? (original) (raw)
Last Updated : 23 Jan, 2023
Given an URL and the task is to parse that URL and retrieve all the related data using JavaScript. Example:
URL: https://www.geeksforgeeks.org/courses When we parse the above URL then we can find hostname: geeksforgeeks.com path: /courses
Method 1: In this method, we will use createElement() method to create a HTML element, anchor tag and then use it for parsing the given URL.
javascript `
// Store the URL into variable var url = "https://geeksforgeeks.org/pathname/?search=query";
// Created a parser using createElement() method var parser = document.createElement("a"); parser.href = url;
// Host of the URL console.log(parser.host);
// Hostname of the URL console.log(parser.hostname );
// Pathname of URL console.log(parser.pathname);
// Search in the URL console.log(parser.search );
`
Output:
geeksforgeeks.org geeksforgeeks.org /pathname/ ?search=query
Method 2: In this method we will use URL() to create a new URL object and then use it for parsing the provided URL.
javascript `
// Store the URL into variable var url = "https://geeksforgeeks.org:3000/pathname/?search=query";
// Created a URL object using URL() method var parser = new URL(url);
// Protocol used in URL console.log(parser.protocol);
// Host of the URL console.log(parser.host);
// Port in the URL console.log(parser.port);
// Hostname of the URL console.log(parser.hostname);
// Search in the URL console.log(parser.search);
// Search parameter in the URL console.log(parser.searchParams);
`
Output:
https: geeksforgeeks.org:3000 3000 geeksforgeeks.org ?search=query search=query