Thursday, June 27, 2024
HomeLanguagesJavascriptHow to parse URL using JavaScript ?

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.neveropen.co.za/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:

neveropen.co.za
neveropen.co.za
/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:
neveropen.co.za:3000
3000
neveropen.co.za
?search=query
search=query

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen 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!

Calisto Chipfumbu
Calisto Chipfumbuhttp://cchipfumbu@gmail.com
I have 5 years' worth of experience in the IT industry, primarily focused on Linux and Database administration. In those years, apart from learning significant technical knowledge, I also became comfortable working in a professional team and adapting to my environment, as I switched through 3 roles in that time.
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments