JS Get Domain URL
Working with URLs plays an important role when you are developing web applications handling data received from external sources in javascript. You can use JavaScript’s built-in URL API to return the specific part of the URL you need. By using this powerful tool, you can get the domain name in just a few lines of code. Apart from JavaScript’s built-in URL API, we can also get the domain URL using the “split()” method, Regular Expressions, etc. No matter any type of URL you have (no “http://” or “https://”, “www” or “www”), you can easily get the domain name URL. So, In this article, we’ll see different ways to get domain URLs in JS.
Before we see how to get a domain URL, let’s understand the difference between a domain name URL and URL. The domain name comes first in the URL, i.e. the name after “www.” is called the domain name and it will have a unique name. For example, In a URL like “https://www.example.com/page“, the domain name URL is “www.example.com“. You can perform a variety of actions by extracting the domain name, such as analyzing and classifying URLs, checking whether a resource is hosted on a specific domain, or performing domain-specific operations.
3 Methods to Get Domain URL
1. URL API
In this method, we will create the URL object with a specific URL string and then extracts the hostname (domain) from that URL.
- Step 1: Create a new
URL object
with the URL string from which you want to get the domain name and stored it in a variable.const url = new URL("https://www.example.com/page");
Here, we have created a new URL object with the URL string “
https://www.example.com/page
” and stored it in a variable “url
‘. We can use this URL object to perform many properties and methods. - Step 2: Extract the hostname from the ‘URL’ object and assign it to the variable.
const hostName = url.hostname;
In this above step, we have extracted the hostname from ‘
url
‘ object by using the “hostname” property and assigning it to the variable “hostname
“. The hostname refers to the domain name portion of the URL, which is “www.example.com
“. - Step 3: Log the variable you stored hostname.
console.log(hostName); // www.example.com
We have logged the value of the ‘
hostName
‘ variable to the console. - Step 4: If you want to remove the “www” prefix from the domain name, use the
replace()
method like below.domain = hostName.replace('www.',''); console.log(domain); // example.com
In this above code, we have replaced “www.” with an empty string by using replace method() and stored the value in the variable ‘
domain
‘. And logged the variable ‘domain’.
2. Split() method
We can also get the domain name from the URL by using the JS ‘split()’ method.
- Step 1: Assign the URL string from which you want to get the domain name to the variable.
const url = "https://www.example.com/page";
In this above example, we have assigned a string “https://www.example.com/page” to the variable “
url
“. - Step 2: Split the string into an array of substrings using the split() method with the “/” character as the separator.
const domain = url.split("/");
Here, we split the url string into an array of substrings using the “
/
” character as the separator and stored it in the variable “domain”. The split() method divides multiple parts at each occurrence of the separator and returns an array. In this case, the variable “domain” contains array ["https:", "", "www.example.com", "page"]
. So, in the next step, we have to print the 2 index value of the array, because it contains the domain name of the URL. - Step 3: Log the 2nd index value of the variable “
domain
”console.log(domain[2]); // Output: www.example.com
You can also set the sort index while splitting, like:
const domain = url.split("/")[2];
console.log(domain); // Output: www.example.com
3. Regular Expressions
In this method, we will use a regular expression pattern to match and extract the domain from the URL string.
- Step 1: Assign the URL string from which you want to get the domain name to the variable.
const url = "https://www.example.com/page";
- Step 2: Extract the domain from the URL using the below regular expression and
match()
function.const domain = url.match(/^(?:https?:\/\/)?(?:[^@\n]+@)?(?:www\.)?([^:\/\n?]+)/)[1];
In the above code, we have extracted the domain name by passing the reg expression into the match function.
-
'^'
– start of the string.- ‘
(?:https?:\/\/)?
‘ – matches an optional “http://” or “https://” at the beginning. - ‘(
?:[^@\n]+@)?
‘ – matches an optional username symbol. - ‘
(?:www\.)?
‘ – This part checks an optional “www.” at the beginning of the domain. '([^:\/\n?]+)
‘ – This part captures one or more characters that are not “:” (colon), “/” (forward slash), “\n” (newline), or “?” (question mark).- ‘
[1]
‘ – accesses the captured domain (the first capturing group) from the match result. - After all, the variable ‘
domain
‘ contains “www.example.com”.
- Step 3: Log the variable that extracted the domain name.
console.log(domain); // Output: www.example.com
How to get the current page domain name?
You can get the current page domain name by using the “window.location” object. In the image below I have used javascript “window.location.hostname
” to get the domain name in the console of a specific “google” page.
You can get “href
“, “origin
“, “hostname
“, “protocol
“, “pathname
” etc. of a specific page using the “window.location
” object.
const href = window.location.href;
console.log(href); // 'https://www.google.com/search?q=run&oq=run&aqs=chrome..69i57j46i131i433i512j4'
const origin = window.location.origin;
console.log(origin ); // https://www.google.com
const hostname = window.location.hostname;
console.log(hostname ); // www.google.com
const protocol = window.location.protocol;
console.log(protocol ); //https
const pathnameL = window.location.pathname;
console.log(pathname); // /search
Conclusion
However, the URL API method is generally recommended to get domain URLs in JS because of its simplicity, reliability, and cross-browser compatibility. When working with URLs, domain name extraction allows you to analyze data based on source origin.