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.
š Neural Networks from Scratch - Presale
I'm writing a book about the timeless foundational concepts of neural networks for JavaScript developers. Go from if-else to weights and biases by building tiny AI models from scratch!
š Neural Networks from Scratch - Presale
I'm writing a book about the timeless foundational concepts of neural networks for JavaScript developers. Go from if-else to weights and biases by building tiny AI models from scratch!