0

I am attempting to split url strings into substrings so that I am only working with the domain name of the website e.g. https://nodejs.org/api/console.html should be nodejs.org and http://postgresql.com should be postgresql.com I have tried solving this issue with the following line of code:

filePath[i].split('/').pop()

But this only works for the urls that do not contain files after the domain e.g. http://postgresql.com

How could I achieve this result?

1 Answer 1

2

JavaScript has a built in interface that handles URLs and their parts, aptly named URL.

You can create an instance of the URL using the source string and then use the hostname parameter to get the domain name.

The following snippet shows this in action:

let urlString = 'https://nodejs.org/api/console.html';
let u = new URL(urlString);
console.log(u.hostname);

More information about the URL interface is here, and specifically the hostname property here.

Note that this is fully supported by all modern browsers and Node.js, but has limited support in IE.

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

Comments

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.