4

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?

3
  • What's your environment? (Example) Commented May 4, 2017 at 19:16
  • angular 2 is my front end and backend is node Commented May 4, 2017 at 19:17
  • 1
    First of all, asking for typescript won't yeld much results for you. Ask for JavaScript; Second of all, what technology you are asking about? Browser, server, IoT?
    – andrew.fox
    Commented May 4, 2017 at 19:18

3 Answers 3

6

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
7
  • It doesnt give me compilation error. However, while running, it throws exception: "URL is undefined". Am I missing something? I am implementing it on node backend Commented May 4, 2017 at 19:35
  • It is supported in node: nodejs.org/api/url.html, but you need to import it: const url = require('url'); Commented May 4, 2017 at 19:39
  • Check my revised answer Commented May 4, 2017 at 19:45
  • import { URL } from "url"; gives me compilation error "[ts] Module '"url"' has no exported member 'URL'. Commented May 4, 2017 at 19:48
  • Weird. That code compiles/runs perfectly well for me. What version of node and it's definition files are you using? What do you get when you run cat node_modules/@types/node/package.json| grep _id ? Commented May 4, 2017 at 19:56
2

You can use HTMLAnchorElement in this purposes

let a = document.createElement("a");
a.href = "http://localhost:8080";

console.log(a.protocol);
console.log(a.host);
console.log(a.port);
1

If you are using Node.js 6 or lower,

import * as url from 'url';
const { protocol, host, port } = url.parse('http://localhost:8080');
console.log(protocol); // http:
console.log(host); // localhost:8080
console.log(port); // 8080

Not the answer you're looking for? Browse other questions tagged or ask your own question.