How to parse URL using JavaScript ?
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.
<script> // Store the URL into variable // Created a parser using createElement() methodvar parser = document.createElement("a");parser.href = url; // Host of the URLdocument.write(parser.host + "<br>"); // Hostname of the URLdocument.write(parser.hostname + "<br>"); // Pathname of URLdocument.write(parser.pathname + "<br>"); // Search in the URLdocument.write(parser.search + "<br>"); </script> |
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.
<script> // Store the URL into variablevar url = // Created a URL object using URL() methodvar parser = new URL(url); // Protocol used in URLdocument.write(parser.protocol + "<br>"); // Host of the URLdocument.write(parser.host + "<br>"); // Port in the URLdocument.write(parser.port + "<br>"); // Hostname of the URLdocument.write(parser.hostname + "<br>"); // Search in the URLdocument.write(parser.search + "<br>"); // Search parameter in the URLdocument.write(parser.searchParams + "<br>"); </script> |
Output:
https: geeksforgeeks.org:3000 3000 geeksforgeeks.org ?search=query search=query


