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.



filter_none

edit
close

play_arrow

link
brightness_4
code

<script>
      
// Store the URL into variable
      
// Created a parser using createElement() method
var parser = document.createElement("a");
parser.href = url;
      
// Host of the URL
document.write(parser.host + "<br>");
      
// Hostname of the URL
document.write(parser.hostname + "<br>");
      
// Pathname of URL
document.write(parser.pathname + "<br>");
      
// Search in the URL
document.write(parser.search + "<br>");
  
</script>

chevron_right


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.

filter_none

edit
close

play_arrow

link
brightness_4
code

<script>
      
// Store the URL into variable
var url = 
      
// Created a URL object using URL() method
var parser = new URL(url);
       
// Protocol used in URL
document.write(parser.protocol + "<br>");
       
// Host of the URL
document.write(parser.host + "<br>");
       
// Port in the URL
document.write(parser.port + "<br>");
       
// Hostname of the URL
document.write(parser.hostname + "<br>");
       
// Search in the URL
document.write(parser.search + "<br>");
       
// Search parameter in the URL
document.write(parser.searchParams + "<br>");
  
</script>

chevron_right


Output:

https:
geeksforgeeks.org:3000
3000
geeksforgeeks.org
?search=query
search=query


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.