How to eliminate subdomains from a string using TypeScript

I am working with a string in TypeScript that follows the format subdomain.domain.com. My goal is to extract just the domain part of the string. For example, subdomain.domain.com should become domain.com.

It's important to note that the 'subdomain' section of the URL can vary in size, so it could be 'subdomain.domain.com' or 'sub.domain.com'. Similarly, the domain itself may differ, such as 'subdomain.domain.com' or 'subdomain.new-domain.com'.

In order to achieve this, I need to remove everything up to and including the first '.' in the string. I hope that clarifies things!

Answer №1

let domainName = 'website.test.com';

let reversedCharacters = domainName.split('').reverse();
let reversedDomain = '', dotCounter = 0;

do {
    if (reversedCharacters[0] === '.') {
        dotCounter++;
        if (dotCounter == 2) break;
    }
    reversedDomain += reversedCharacters[0];
    reversedCharacters.splice(0, 1);
} while (dotCounter < 2 && reversedCharacters.length > 0);

let rootDomain = reversedDomain.split('').reverse().join('');

This code snippet removes subdomains from a domain name and returns the root domain.

Answer №2

To extract the last 2 elements of a URL and combine them into a new string, you can split the URL by '.' and then manipulate the resulting array accordingly.

function extractDomain(url: string) {
    const segments = url.split('.');
    const lastTwo = segments.slice(-2).join('.');
    
    try {
        // Check if it's a valid URL with a protocol
        const instance = new URL(url);
        return `${instance.protocol}//${lastTwo}`;
    } catch (_) {
        return lastTwo;
    }
}

extractDomain('https://subdomain.example.com') // https://example.com
extractDomain('subdomain.example.com') // example.com
extractDomain('https://subdomain.another-subdomain.example.com') // https://example.com

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

Obtaining a string value from a parallel array

Apologies for the very basic question, but I'm struggling with this. I have a word. Each letter of the word corresponds to a position in one array, and then returns the character at the same position from a parallel array (basic cipher). Here is my c ...

Issue with Orgchart JS: The requested resource does not have the 'Access-Control-Allow-Origin' header present

Currently, I am developing a program to create organization charts using orgchart.js and simple PHP. This project does not involve any frameworks, but unfortunately, I encountered the following error: CORS policy is blocking access to XMLHttpRequest at & ...

What is the process for syncing ng-model with external data sources?

Here is a question that I have pondered: Let's consider the HTML code snippet below: <div id="container" ng-controller="Controller"> <my-tag ng-model="values"></my-tag> </div> Now, take a look at the controller defined a ...

Developing a discriminated union by utilizing the attribute names from a different type

In my quest to create a unique generic type, I am experimenting with extracting property names and types from a given type to create a discriminated union type. Take for example: type FooBar = { foo: string; bar: number; }; This would translate t ...

Is there a way to simulate a click event (on a file type input) within a promise?

I've been struggling with this issue for a long time and have not been able to find a solution. The problem arises when attempting to trigger a click event on a file input type from within a promise. When I directly trigger the event inside the promis ...

Implementing JavaScript to Take an Array of Integers from an HTML Input Field and Sort It

Task: Retrieve 10 Array Values from HTML Input Field and Arrange Them in Ascending Order In order to add 10 values from an HTML input field to a JavaScript array, I have created an input field through which data is passed to the array in JS. Two labels ar ...

Chrome has some issues with resizing the SVG Pattern element

Utilizing inline svgs, I have a svg circle filled with a pattern that should cover 100% of the container size. However, when the parent element is resized via JavaScript, the pattern no longer reflects the 100% width and height as expected. This issue seem ...

Angular: Maximizing Input and Output

I'm having trouble with the function displaying within the input field. My goal is to simply allow the user to enter a name and have it displayed back to them. HTML: <div ng-app = "mainApp" ng-controller = "studentController"> <tr> < ...

Tips for utilizing window.scrollTo in tandem with react/material UI?

I have a simple functional component that displays an alert panel with an error message under certain conditions. The issue I am facing is that when the alert panel is rendered due to an error, it might be off-screen if the user has scrolled down. To addre ...

Analog Clock Time Adjustment Bubble Deviation Dilemma

Recently, I encountered an issue with an analog clock component. Every time I click on the time adjustment bubble repeatedly while also moving the cursor position, it tends to drift away from its original placement, which should ideally be between an orang ...

The object for checking Ajax connections is not providing any values

I've been working on creating a unique AJAX connection check object, but unfortunately I'm struggling to get it to function properly. :/ Here's the object structure: function Connection(data){ this.isConnected = false, this.check = funct ...

What is the best way to ensure that GCM push notifications are still received even when the app is closed or the

Currently, I'm in the process of developing an application using Ionic 2 that requires push notifications to be received. In certain scenarios, such as when the app is force-stopped on Android or when the device is turned off, push notifications are ...

How can you use jQuery to remove a class from an element after a specified period of time?

After updating a record in the database, I plan to make modifications using an AJAX request. Once that is done, I will dynamically add a class to the rendered div by utilizing the addClass method. The class being added (we'll refer to it as colored) c ...

Identify the browser dimensions and implement CSS styling for all screen resolutions

I am currently facing an issue with a function that I have created to apply CSS changes to a menu based on browser resizing and different resolutions. The problem lies in the fact that my function does not seem to be correctly interpreted by the browser. W ...

Is it possible to concurrently hot module reload both the server (.NET Core) and client (Angular)?

Using the command 'dotnet watch run' to monitor changes in server code and 'ng build --watch' for Angular code updates has been successful. It rebuilds the code correctly into directories "bin/" and "wwwroot/" respectively. myapp.cspro ...

Problem with rendering React Router v4 ConnectedRouter on nested routes

The routes for the first level are correctly displayed from Layout.tsx, but when clicked on ResourcesUI.tsx, the content is not rendered as expected (see code below). The ResourceUI component consists of 2 sections. The left section contains links, and th ...

What is the process of integrating an ejs view engine with express on Netlify?

Need help configuring the ejs view engine with netlify I attempted to set app.set('view engine', 'ejs'), but didn't see any results. const express = require('express'); const path = require('path'); const serv ...

Display a loading indicator or progress bar when creating an Excel file using PHPExcel

I am currently using PHPExcel to create excel files. However, some of the files are quite large and it takes a significant amount of time to generate them. During the file generation process, I would like to display a popup with a progress bar or a waitin ...

Firing ng-change with fileModel or input type="file"

Is there a way to trigger ng-change when a change occurs with this file directive? I have implemented a custom file directive for this purpose. The Directive: app.directive('ngFileModel', ['$parse', function($parse) { return { ...

Discover the Magic Trick: Automatically Dismissing Alerts with Twitter Bootstrap

I'm currently utilizing the amazing Twitter Bootstrap CSS framework for my project. When it comes to displaying messages to users, I am using the alerts JavaScript JS and CSS. For those curious, you can find more information about it here: http://get ...