Having trouble extracting the Top-Level Domain from a URL

I'm struggling to find a reliable way to extract the Top-Level Domain from a URL. The challenge I'm facing is that the URLs entered by users can vary greatly - they might enter www.google.com, m.google.com, m.google.uk, google.uk, or www.m.google.com.

I attempted using the slice method, but it didn't yield the desired results because some URLs contain 2 or 3 characters. Splitting based on "." also proved problematic as the number of resulting parts could be 2, 3, or even 4. Is there a JavaScript function available that can accomplish this in a single line? Are there any convenient custom functions to tackle this?

Most resources suggest retrieving the host name, but my goal is to specifically isolate the last 2 or 3 characters of the URL (such as com, uk, cn, etc.). While I could implement multiple if-else loops, I'd prefer a simpler solution that avoids this level of complexity.

I aim to obtain an output like 'com', 'uk', or 'cn' depending on the top-level domain in the URL. Since users input the URL, predicting whether they will type m.google.com, www.m.google.com, www.google.com, or simply google.com adds an additional layer of uncertainty.

Answer №1

An effective strategy to achieve this:

const detector = document.createElement('a');

detector.href = "http://www.yahoo.com/path/";
console.log(detector.hostname); // "www.yahoo.com"

detector.href = "http://m.yahoo.com/path/";
console.log(detector.hostname); // "m.yahoo.com"

detector.href = "http://www.m.yahoo.com/path/";
console.log(detector.hostname); // "www.m.yahoo.com"

Answer №2

I've found success with the code below. Big thanks to @StephenP for your assistance. Also, shoutout to @Timo although it seems Document is not recognized in the protractor library.

var parser = TextBox.siteName;//retrieve user input for site into parser variable.
 var hostParts = parser.split('.');
    var URLdomain = hostParts[hostParts.length - 1];

Answer №3

To determine the Top Level Domain (TLD), look for the final period (.) after isolating the domain.

Try testing it here: https://example.com/sample-link

var websites = [
  'apple.net',              // should show 'net'
  'https://bing.org.au',     // should display 'au'
  'amazon.jp/products/item', // should indicate 'jp'
  'ftp:///usr/docs'          // should not work
];

for (var key in addresses) {
    console.log(getTLD(websites[key]));
}

function getTLD(url) {
    // manage exceptions
    if (typeof url == 'undefined' || url.indexOf('ftp:///') != -1)
        return undefined;

    var section = url;

    // eliminate http://
    if (section.includes('//'))
        section = part.split('//')[1];

    // isolate the domain
    if (part.includes('/'))
        section = part.split('/')[0];  

    // identify TLD
    if (section.includes('.')) {
        var allParts = section.split('.');
        section = allParts[allParts.length - 1]; 
    }
    return section;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

An error stating that "DataTable is not a recognized function" occurred within the document function

Previously, I set up datatables using the code below: $(function () { $('#keywords-table').DataTable({ "ajax": ({ url: "{{ route('getKeywordsByProductId') }}", method: "get", ...

Action of the Floater Button in Material UI

I'm currently working with Material UI's floater button component and I am having trouble getting it to open a menu onClick as intended. It is frustrating that there are no example codes available that demonstrate how to make the menu appear when ...

Retrieving information from a PHP server using AJAX

Searching for a way to retrieve the posts created by users and load more posts upon user's request. Encountering an Unexpected end of JSON input error when initiating an ajax request in the console. Javascript $("#ajax_load_more").click(function ...

Infinite dice roller for a six-sided die

Looking for assistance with a School JavaScript assignment focusing on creating a 6-sided dice roller program? Need some guidance on how to approach this task? The program should allow users to choose how many dices to roll, ranging from 1 to 5. The sum o ...

I am looking to incorporate two YouTube videos into an HTML webpage, each in a different language. I would like to provide the option for users to select the language, even though the content

I am looking to target a global audience with my website, so the content is in English. However, I want to offer users the option to watch videos in their preferred language. I have recorded content in 4 different languages that might enhance engagement on ...

I'm attempting to install the "firebase" package using npm, but I keep encountering a python-related error message during the installation process

I am experiencing difficulties while attempting to install the firebase package in a local expo-managed project. Unfortunately, I keep receiving the following error message... Here is the error message that I am encountering I have already tried using "e ...

Ways to align and fix a button within a specific div element

How can I make the button with position: fixed property only visible inside the second div and not remain fixed when scrolling to the first or last div? .one{ height:600px; width: 100%; background-color: re ...

"JavaScript throws an 'Undefined' error when trying to access a basic

I am struggling with a basic set of HTML and JS files that are not functioning properly, and I can't seem to pinpoint the issue: <html> <head> <script type="text/javascript" src="data.json"></script> < ...

Applying conditional statements to an array's parent elements during iterations in JavaScript

Here is my complete script for relevance. I am currently looping through an array from a JSON object and populating content into an HTML div based on the content's ID. The process works well, but I am facing an issue with the logic related to the par ...

What is the method for configuring my bot to forward all logs to a specific channel?

const logsChannel = message.guild.channels.cache.find(channel => channel.name === 'logs'); I am looking to set up my bot to send log messages for various events, like member join/leave or message deletion, specifically in a channel named &apo ...

Building a Div Tag Layout with CSS for Full Width and Left Position of 300px

Experiencing some trouble with styling a div element. My goal is to have the div start at left:300px and stretch across the entire width of the browser window. However, when I apply width:100%, the div extends beyond the boundaries of the browser screen. ...

developing an associative object/map in JavaScript

I have a form featuring various groups of checkboxes and I am attempting to gather all the selected values into an array, then pass that data into an Ajax request. $('#accessoriesOptions input').each(function(index, value){ if($(this).prop(& ...

Include an option for whitespace characters when validating a file using regex

My text box has specific criteria for what is considered good or bad input. Examples of good input could include: GoodString GoodString88 99GoodString I want to avoid certain types of bad input, such as: Good*String Good&String However, I do want ...

What is the best way to locate and send a message to a particular channel within a server?

I've been working on a Discord bot using Discord.js and I'm currently attempting to create a welcome command. My goal is to send a message to a specific channel within my server. However, due to recent updates in discord.js, I'm having troub ...

Instructions for subtracting the value of a cell in column 22 from a cell in column 24 within the same row when a change trigger occurs utilizing Google Apps Script

I need help modifying the script below to only subtract the row on which the change is made, instead of subtracting all rows in the sheet when the on-change trigger executes. var sourceSpreadsheetID = '1r4e4BNKwsmdC2Ry93Mq-N49zj3DAZVpHG21TgTe0FWY&a ...

How can one determine the most accurate box-shadow values?

I am trying to extract the precise box-shadow parameters from a CSS style rule generated by the server. My main focus is determining whether the element actually displays a visible shadow or not. There are instances where the shadow rule is set as somethi ...

The method for inputting information into a frame using selenium

Currently, I am utilizing Selenium with Python to input username and email data that are within a frame. You can find the inputs by going to this link. However, I am facing an issue where the program is unable to switch into the modal. try: time.slee ...

Ways to dynamically eliminate focus around text inputs

I have created an HTML page and here is the link to it: https://i.sstatic.net/n8UdU.png My main goal is to remove the black border around the text input on this page. The challenge I am facing is that the 'things to do' list is generated dynamic ...

How can I retrieve JSON data from an AJAX request on an HTML page?

How can I display my JSON data on an HTML page using this JavaScript code? $.ajax({ url : 'auth.json', type: "GET", dataType : "jsonp", success: function(result) { $.each(result, function(i, v) { // Loop through each record in ...

Show/Hide a row in a table with a text input based on the selected dropdown choice using Javascript

Can someone please assist me with this issue? When I choose Business/Corporate from the dropdown menu, the table row becomes visible as expected. However, when I switch back to Residential/Consumer, the row does not hide. My goal is to only display the row ...