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.
š Build a full trivia game app with LangChain
Learn by doing with this FREE ebook! This 35-page guide walks you through every step of building your first fully functional AI-powered app using JavaScript and LangChain.js
š Build a full trivia game app with LangChain
Learn by doing with this FREE ebook! This 35-page guide walks you through every step of building your first fully functional AI-powered app using JavaScript and LangChain.js