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.

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Web Develop Wolf
  • 5,996
  • 12
  • 52
  • 101
  • 2
    Does this answer your question? [How to remove part of a string before a ":" in javascript?](https://stackoverflow.com/questions/4092325/how-to-remove-part-of-a-string-before-a-in-javascript) (just replace ":" with ".") – Heretic Monkey Aug 04 '21 at 15:13
  • No because I noticed there was a note that if there's multiple ':' in the string it will only work on the last one it encounters - with this being a domain name it has the three '.' in it so I'm worried that solution won't work – Web Develop Wolf Aug 04 '21 at 15:15
  • 2
    There are three solutions presented in the answer. Did you try any of them? The warning is only for the second of the three. – Heretic Monkey Aug 04 '21 at 15:18
  • What did you try so far ? did you try using regex for example ? – Wahalez Aug 04 '21 at 15:19
  • There is also [Remove part of the string before the FIRST dot with js](https://stackoverflow.com/q/65901022/215552) or [Get domain name without subdomains using JavaScript?](https://stackoverflow.com/q/9752963/215552) – Heretic Monkey Aug 04 '21 at 15:28

2 Answers2

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.

Praveen Thirumurugan
  • 977
  • 1
  • 12
  • 27
-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