How to parse URL using JavaScript ?
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
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
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...