The Wayback Machine - https://web.archive.org/web/20241111231132/https://www.geeksforgeeks.org/how-to-get-url-and-url-parts-in-javascript/
Open In App

How To Get URL And URL Parts In JavaScript?

Last Updated : 25 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In web development, working with URLs is a common task. Whether we need to extract parts of a URL or manipulate the URL for navigation, JavaScript provides multiple approaches to access and modify URL parts. we will explore different approaches to retrieve the full URL and its various components.

These are the following approaches to get URL And URL Parts In JavaScript:

Using window.Location Object

The window.location object contains information about the current URL of the document. It provides various properties to access different parts of the URL.

Syntax:

window.location.href; // Full URL
window.location.hostname; // Domain name
window.location.pathname; // Pathname
window.location.protocol; // Protocol (http/https)
window.location.search; // Query string
window.location.hash; // Fragment (anchor part)

Example: This example retrieves different parts of the URL using a window. Location. It’s particularly useful for accessing the current URL of the webpage.

JavaScript
// index.js

// Accessing different parts of the current URL
// Full URL
console.log(window.location.href);

// Domain name
console.log(window.location.hostname);

// Pathname
console.log(window.location.pathname);

// Protocol
console.log(window.location.protocol);

// Query string
console.log(window.location.search);

// Fragment identifier
console.log(window.location.hash); 

Output:

as
OUtput

Using URL Constructor

The URL constructor provides a more flexible way to work with URLs in JavaScript. We can create a new URL object and extract various components from it.

Syntax:

let url = new URL(urlString);
url.href; // Full URL
url.hostname; // Domain name
url.pathname; // Pathname
url.protocol; // Protocol
url.search; // Query string
url.hash; // Fragment identifier

Example: The URL constructor is a flexible way to parse a URL string and extract its components. It works for URLs outside the current window, unlike window.location, which only works for the current page's URL.

JavaScript
// index.js

// Create a new URL object from a string
const url = new URL("https://www.example.com:8080/page?name=John#section1");

// Full URL
console.log(url.href); 

// Domain name
console.log(url.hostname);

// Pathname
console.log(url.pathname);

// Protocol
console.log(url.protocol);

// Query string
console.log(url.search);

// Fragment identifier
console.log(url.hash); 

Output
https://www.example.com:8080/page?name=John#section1
www.example.com
/page
https:
?name=John
#section1

Using split() Method on URL String

If we don't need the complexity of objects like window.location or URL, a simple string manipulation using split() can be used to extract different parts of the URL manually.

Syntax:

urlString.split(delimiter); // Split the URL by the delimiter

Example: This method manually splits the URL string based on known delimiters (://, /, :) to extract components. It's a quick way to get URL parts without using any built-in objects, though it’s less robust compared to other approaches.

JavaScript
// index.js

// URL string
const urlString = "https://www.example.com:8080/page?name=John#section1";

// Splitting the URL by different delimiters
const [protocol, rest] = urlString.split("://");
const [domainAndPort, pathAndQuery] = rest.split("/");
const [domain, port] = domainAndPort.split(":");

// Protocol
console.log(protocol);

// Domain
console.log(domain);

// Port
console.log(port);

// Path and Query
console.log(pathAndQuery); 

Output
https
www.example.com
8080
page?name=John#section1

Similar Reads

Convert relative path URL to absolute path URL using JavaScript
Given a relative URL, the task is to convert the relative URL to an absolute URL. Here, the base URL is also given. 2 approaches are discussed here, the first example has the baseURL provided by the user and the second takes it from the URL of the page. Approach 1: Get the relURL and baseURL from user.Use .split() method to split the base and relat
3 min read
How to get protocol, domain and port from URL using JavaScript ?
The protocol, domain, and port of the current page can be found by two methods: Method 1: Using location.protocol, location.hostname, location.port methods: The location interface has various methods that can be used to return the required properties. The location.protocol property is used to return the protocol scheme of the URL along with the fin
2 min read
What is URL Locator & what are common schemes used for the URL in HTML ?
Every HTML document on the internet has a unique URL. URL stands for Uniform Resource Locator. The URL is the HTML document's address on the internet. Any file that can be accessed via the internet has a URL, including images, JavaScript files, CSS files, Flash files, and so on. To view an HTML document in a browser, enter the URL of the document i
2 min read
JavaScript method to get the URL without query string
The task is to get the URL name of the page without using a query string with the help of JavaScript. replace() method: This method searches a string for a defined value, or a regular expression, and returns a new string with the replaced defined value. Syntax: string.replace(searchVal, newvalue) Parameters: searchVal: This parameter is required. I
3 min read
Get the YouTube video ID from a URL using JavaScript
Given a YouTube Video URL, the task is to get the Video ID from the URL using JavaScript. Here are a few methods discussed. JavaScript split() Method: This method is used to split a string into an array of substrings, and returns the new array. Syntax: string.split(separator, limit) Parameters: separator: This parameter is optional. It specifies th
2 min read
How to get an object containing parameters of current URL in JavaScript ?
The purpose of this article is to get an object which contains the parameter of the current URL. Example: Input: www.geeksforgeeks.org/search?name=john&age=27 Output: { name: "john", age: 27 } Input: geeksforgeeks.org Output: {} To achieve this, we follow the following steps. Create an empty object.Using the String.match() method extract all th
2 min read
JavaScript Know the value of GET parameters from URL
In this article, we will see how to get the GET parameters from a URL using JavaScript. In order to know the parameters that are passed by the "GET" method, sometimes we need to pass the Email and other details. For that purpose, we are using the following snippet of code. Example 1: This example get the value of "a" parameter from the URL. C/C++ C
1 min read
How to get the file name from page URL using JavaScript ?
JavaScript provides multiple techniques for string manipulation and pattern matching. By demonstrating various methods, the article equips developers with versatile solutions to dynamically retrieve and utilize file names from different URL formats within their applications. There are several approaches to getting the file name from the page URL us
3 min read
How to Get Browser to Navigate URL in JavaScript?
As a web developer, you may need to navigate to a specific URL from your JavaScript code. This can be done by accessing the browser's window object and using one of the available methods for changing the current URL. In JavaScript, there are several approaches for navigating to a URL. The most commonly used methods are: Using window.location.hrefTh
4 min read
How to get the new image URL after refreshing the image using JavaScript ?
The browser cache relies on the image URL to decide whether the image is the same or not and whether to use the stored version. It means if we change something within the URL and then attempt to reload the image, the cache will no longer be able to change that it is the same resource. The cache will fetch it again from the server. Approach: To chan
2 min read
How to get the current URL using JavaScript ?
The current URL can be accessed using the URL property of the Document object in JavaScript. This property returns a string with the full location of the webpage, including the HTTP protocol, allowing you to retrieve and manipulate the complete URL of the current page. We can get the current URL using Javascript in two ways: Document.URLwindow.loca
2 min read
How to get URL Parameters using JavaScript ?
To get URL parameters using JavaScript means extracting the query string values from a URL. URL parameters, found after the ? in a URL, pass data like search terms or user information. JavaScript can parse these parameters, allowing you to programmatically access or manipulate their values. For getting the URL parameters, there are 2 ways: Table of
3 min read
How to Get Domain Name From URL in JavaScript?
In JavaScript, the URL object allows you to easily parse URLs and access their components. This is useful when you need to extract specific parts of a URL, such as the domain name. The hostname property of the URL object provides the domain name of the URL. PrerequisiteJavascriptHTMLBelow are the following approaches to get a domain name from a URL
2 min read
How to match multiple parts of a string using RegExp in JavaScript ?
In this article, we will try to understand how we could match multiple parts of a string using Regular Expression (RegExp) in JavaScript with the help of both theoretical explanations as well as coding examples too. Let us first understand some below enlightened theoretical details about Regular Expressions in JavaScript and the actual object (RegE
2 min read
Get the full URL in PHP
In this article, we will see how to get the complete URL of currently running pages using PHP, along with understanding their implementation through the examples. $_SERVER is a super global variable in PHP that contains the details related to the header, paths, and script locations. The status of HTTPS will be saved in the Global variable $_SERVER[
3 min read
Firebase to get url
What is Firebase? Firebase is a platform which allows you to build web and mobile applications without server side programming language. It stores users data on its real-time database which sync data among the users in real-time. It is a google product and offers us a variety of features. Some key features of Firebase are: Firebase hostingReal time
4 min read
How to get the fragment identifier from a URL ?
A fragment identifier is a string of characters that refers to a resource that is inferior to a primary resource. Approach 1: We are able to print the fragment identifier by defining a new variable as location. hash and then display it with the help of document.getElementbyId() method. Syntax: var x = location.hash; document.getElementById("demo").
1 min read
How to get the current URL using AngularJS ?
In this article, we will see how to get the current URL with the help of AngularJS, along with knowing its basic implementation through the examples. This task can be accomplished in 2 ways, i.e., by implementing the $location.absURL() method to get the complete URL of the current page, & the 2nd-way implements the split() method that is append
2 min read
How to get complete current page URL in PHP ?
In PHP. there is a superglobal variable that can provide you with the URL of the current working page. The $_SERVER is an inbuilt variable that can access the page URL, after that, you have to check that the URL is following which type of HTTP protocol. What is Superglobal? Superglobals are already defined variables by the PHP engine which can be u
1 min read
How to access data sent through URL with GET method in PHP ?
On a website, we often use forms to collect data, login/signup boxes for users, a search box to search through a web page, etc. So input fields are used to make the website interactive and to collect data. But we know that HTML can not store the data in a database so for that we use a backend scripting language like PHP. URLs structure for GET meth
2 min read
Get the current URL using jQuery
The current URL in jQuery can be obtained by using the 'href' property of the Location object which contains information about the current URL. The href property returns a string with the full URL of the current page. We can access the value of the href property using two different methods of jQuery. Table of Content Using the attr() methodUsing th
2 min read
How to get the Current URL in PHP ?
In PHP, Getting the current URL is a common requirement for various tasks such as building dynamic navigation menus, tracking user activity, or generating links. PHP provides several superglobal arrays and functions to retrieve different parts of the URL, including the protocol, domain, path, query parameters, etc. ApproachUsing $_SERVER['REQUEST_U
1 min read
How to get the Base URL with PHP ?
The term "Base URL" refers to the base or starting point for a set of related URLs. For example, if you have a website with multiple pages or an API with various endpoints, the Base URL is the common part shared by all those URLs. It typically includes the protocol (such as "http" or "https"), the domain name (e.g., "example.com"), and sometimes a
2 min read
How To Get The URL Parameters Using AngularJS?
In AngularJS, retrieving URL parameters is essential for managing dynamic content and user interactions based on the URL state. In this article, we'll learn various approaches to achieve this. Table of Content Approach 1: Using ActivatedRoute ServiceApproach 2: Using Router ServiceApproach 3: Using URLSearchParamsSteps To Get URL ParametersStep 1:
3 min read
How to Get Query Parameters from URL in Next.js?
In Next.js, getting query parameters from the URL involves extracting key-value pairs from the URL string to access specific data or parameters associated with a web page or application, aiding in dynamic content generation and customization. To get query parameters from the URL in next.js we have multiple approaches mentioned below: Table of Conte
5 min read
How to Get The Current URL Domain in Next.js ?
In Next.js, we can get current url domain with the help of built-in methods like window and document location. In this article, we'll explore different approaches and best practices for obtaining the current URL domain in Next.js applications. The approaches to get the URL of the current domain in next.js are given below: Table of Content Using win
3 min read
How to Get URL pathname in Next.js?
Next.js is a powerful React framework that simplifies the process of building server-rendered and statically generated web applications. One common requirement in web development is to get the URL pathname, which can be useful for various purposes such as conditional rendering, routing, and analytics. In this article, we will explore different meth
3 min read
How to get url after "#" in Express Middleware Request ?
In Express, the fragment identifier (the part of the URL after the # symbol) is not directly accessible on the server side because it is not sent to the server as part of the HTTP request. The fragment identifier is typically used for client-side navigation and is processed on the client side only. If we need to access data from the fragment identi
3 min read
How to get full URL in Express.js ?
Express is a small framework that sits on top of Node.js’s web server functionality to simplify its APIs and add helpful new features. It makes it easier to organize your application’s functionality with middleware and routing. It adds helpful utilities to Node.js’s HTTP object and it facilitates the rendering of dynamic HTTP objects. Use the follo
2 min read
Node.js Error: Cannot GET/ from Running the URL on the Web Browser
The "Cannot GET /" error in Node.js typically occurs when you try to access a route in your web browser that hasn't been defined in your application. This common issue can be resolved by ensuring that your server is correctly set up to handle incoming requests at the root path or other specified paths. Understanding the ErrorWhen you see the "Canno
3 min read
Article Tags :
three90RightbarBannerImg