typescript从包含url的字符串中获取主机名,协议,端口

时间:2017-05-04 19:13:53

标签: javascript url typescript

如果我有一个像http://localhost:8080这样的字符串 我想提取url的不同部分,比如协议http,域名(localhost)和端口(8080),什么是打字稿中最好的方法?

我可以对字符串进行简单的解析来获取不同的值。但不确定这是否是最好/最干净的方法。我应该首先将此字符串转换为有效的URL(使用某个库),然后从中获取主机名,协议和端口吗? Java会有这样的库,很容易让我这样做但是如何用typescript实现同样的目标呢?

3 个答案:

答案 0 :(得分:1)

您可以使用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

它并未在所有浏览器中实现,但如果您想使用它,可以找到它的polyfill。

修改

在节点中,您可以执行以下操作:

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

如果您收到此compilaiton错误:

  

错误TS2307:找不到模块' url'

然后你需要节点定义:

npm install @types/node

答案 1 :(得分:1)

如果您使用的是Node.js 6或更低版本,

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

答案 2 :(得分:0)

您可以在此目的中使用HTMLAnchorElement

colorRampPalette(rev(brewer.pal(n=7,name="RdYlBu")))
相关问题