Get Domain Name from a full URL

Hi All

This is an easy one - just not easy for me :slight_smile:

I'm looking to use an API to check the spam status of a user submitted full URL and I'd like to extract just the domain name from it, so I need to turn this:
https://www.example.com/test-folder/another/folder

into this:

example.com

I've tried this on the front part:
testurl.replace('https://', '').replace('http://', '').replace('www.', '')
but what about removing everything after the forward slash?

I've tried a few variations on 'split' but am missing something simple.

Hey Tom.

Can you check on browser component?
here is a link from the other Tom!

Having removed the http//,https//,.www. parts a simple split on "/" should do it i.e.

If the url from above is trimmedurl then:

trimmedurl.split("/")[0]

If that is wrong syntax use

parts = trimmedurl.split("/")

Then parts[0]

3 Likes

is this in server connect?
node?

Custom formatter could be the way to go

This was the correct one, thank you @Hyperbytes

Thank you too @famousmag - I forgot to add it was server side NodeJS (DUH) but I'm going to try it on the front end using the Browser component like you mentioned just for future reference, appreciate your help.

1 Like

i think he is validating a url sent to site via api rather than where the site is running

Thats correct Brian - it's all working like a treat.

1 Like

Yeah... My apologies guys!!! I read it but didn't get it... :blush:

Here is a custom server connect formatter to to extract domain from a url if you want to try it. Just drop it into your extensions/server_connect/formatters folder and you will see it as below

getdomain.zip (676 Bytes)

Formatters make life so easy, all it needed was

exports.getdomain = function (data) {
    let url = new URL(data);
    return url.hostname;
}
4 Likes