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: neveropen.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       // 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 = Â Â Â Â Â Â // 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