šŸ“• LangChain for JavaScript developers is now out!
Build 5 Next.js apps with ChatGPT integrated features using LangChain.

Get the domain from a URL string in JavaScript

Let's say we have the following URL represented as a JavaScript string:

const str = "https://www.js-craft.io/blog/some-article"

If we want to extract just the domain www.js-craft.io from this URL we can use a function like the one below:

const getDomain = (str) => {
  let url = new URL(str)
  return url.hostname
}

const str = "https://www.js-craft.io/blog/some-article"
getDomain(str) // www.js-craft.io

If we want to also clean it up and remove the www we can add a second parameter and use the replace() method:

const getDomain = (str, stripWWW = false) => {
  let url = new URL(str)
  const {hostname:host} = url
  return stripWWW ? host.replace('www.','') : host
}

const str = "https://www.js-craft.io/blog/some-article"
getDomain(str, true) // js-craft.io
getDomain(str) // www.js-craft.io

Note that if we don't pass a valid formatted URL string the Javascript URL() constructor will throw the following exception:

Uncaught TypeError: Failed to construct 'URL': Invalid URL

I've made this example and you can see the full code on my Github.

We can also extract some additional properties using the URL constructor such as pathname or protocol:

url.pathname // blog
url.protocol // https

See the full list of properties here.

šŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.

šŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.


Leave a Reply

Your email address will not be published. Required fields are marked *