1

I have a string in TypeScript which is subdomain.domain.com I want to create a new string that is just the domain on its own, so for example subdomain.domain.com would become domain.com

Note: The 'subdomain' part of the URL could be different sizes so it could be 'subdomain.domain.com' or it might be 'sub.domain.com' so I can't do this on character size. The domain might also be different so it could be 'subdomain.domain.com' or it could be 'subdomain.new-domain.com'.

So basically I need to just remove up to and including the first '.' - hope that all makes sense.

5

2 Answers 2

0
var domain = 'mail.testing.praveent.com';

var domainCharacters = domain.split('').reverse();
var domainReversed = '', dotCount = 0;

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

var domainWithoutSubdomain = domainReversed.split('').reverse().join('');

This will strip off the subdomains in a domain and give the root (@) domain name alone.

Sign up to request clarification or add additional context in comments.

2 Comments

This won't work from urls like mail.testing.praveent.co.uk
Nice catch. In this case, we would need to save a map of all TLDs and check against them to find the number of dot chains to filter.
-1

You can split it by . and get only the last 2 elements and turn it back into a string again.

function strip(url: string) {
    const fragments = url.split('.');
    const last = fragments.pop();
    try {
        // if its a valid url with a protocol (http/https)
        const instance = new URL(url);
        return `${instance.protocol}//${fragments.pop()}.${last}`;
    } catch (_) {
        return `${fragments.pop()}.${last}`;
    }
}

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

4 Comments

This will not strip off multiple sub-domains in a single string.
You're right, I didn't know multiple sub-domains was possible up until now. But it does work if it's not multiple sub-domains.
Also, try with subdomain-demo-example.com. This is a valid domain but the function returns just com as response.
I edited the answer. Hope I got it right.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.