Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

typescript get hostname, protocol, port from a string containging url

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?

like image 426
user1892775 Avatar asked Sep 16 '25 13:09

user1892775


1 Answers

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.


Edit

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
like image 55
Nitzan Tomer Avatar answered Sep 18 '25 08:09

Nitzan Tomer