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
var parser = document.createElement( "a" );
parser.href = url;
console.log(parser.host);
console.log(parser.hostname );
console.log(parser.pathname);
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
var url =
var parser = new URL(url);
console.log(parser.protocol);
console.log(parser.host);
console.log(parser.port);
console.log(parser.hostname);
console.log(parser.search);
console.log(parser.searchParams);
|
Output:
https:
geeksforgeeks.org:3000
3000
geeksforgeeks.org
?search=query
search=query
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
23 Jan, 2023
Like Article
Save Article