if I have a string like http://localhost:8080 and I want to extract the different parts of the of url, like the protocol http, domain name (localhost) and port (8080), what is the best way to do in typescript?
I can do a simple parse of the string to get the different values. But not sure if that is the best/cleanest way to do it. Should I first convert this string to a valid URL (using some library) and then get the hostname, protocol and port from it? Java would have such libraries that would easily let me do that but how do I achieve the same with typescript?
You can use the URL class:
let url = new URL("http://localhost:8080");
console.log(url.protocol); // http:
console.log(url.host); // localhost:8080
console.log(url.port); // 8080
(code in playground)
It is not implemented in all browsers but you can find polyfills for it if you want to work with it.
In node you can do this:
import { URL } from "url";
let url = new URL("http://localhost:8080");
console.log(url.protocol); // http:
console.log(url.host); // localhost:8080
console.log(url.port); // 8080
If you get this compilaiton error:
error TS2307: Cannot find module 'url'
Then you need the node definitions:
npm install @types/node
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With