The new URL(url) constructor parses the URL and creates a URL object. This object has various properties that represent different parts of the URL. The hostname property of the URL object returns the domain name. For instance, for the URL https://www.example.com/path/to/resource?query=param, urlObject.hostname would return www.example.com. If the URL is invalid, the URL constructor will throw an error. In the catch block, you can handle this error, for example by logging it or returning a default value.
Example: This example shows the extraction of the domain name from a URL.
HTML
<!DOCTYPE html><htmllang="en"><head><metacharset="UTF-8"><metaname="viewport"content="width=device-width, initial-scale=1.0"><title>Document</title></head><body><h1>How to get domain name from URL in JavaScript</h1><p>Domain Name : <spanid="span"></span></p><scriptsrc="Index.js"></script></body></html>
JavaScript
constspan=document.getElementById('span');// Function to get the domain name from a URLfunctiongetDomainName(url){try{// Create a URL objectconsturlObject=newURL(url);// Return the hostname (domain name)returnurlObject.hostname;}catch(error){console.error("Invalid URL:",error);returnnull;}}// Example usageconsturl="https://www.example.com/path/to/resource?query=param";constdomainName=getDomainName(url);span.innerHTML=domainName;console.log("Domain Name:",domainName);
Output:
URL object
Using Regular Expressions
If you want more control or need to support environments where the URL object is not available, you can use regular expressions to extract the domain from the URL string.
Example: This example demonstrates the extraction of the domain name using Regex.
HTML
<!DOCTYPE html><htmllang="en"><head><metacharset="UTF-8"><metaname="viewport"content="width=device-width, initial-scale=1.0"><title>Document</title></head><body><h1>How to get domain name from URL in JavaScript</h1><p>Domain Name : <spanid="span"></span></p><scriptsrc="Index.js"></script></body></html>
JavaScript
constspan=document.getElementById('span');functiongetDomainFromUrl(url){constregex=/^(?:http?:\/\/)?(?:www\.)?([^\/]+)/i;constmatch=url.match(regex);returnmatch?match[1]:null;// Return the domain if found}// Usageconstdomain=getDomainFromUrl('https://www.contoh.co.id/path?query=param');console.log(domain);// Output: "contoh.co.id"span.innerHTML=domain;
Tidak ada komentar:
Posting Komentar