如果我有一个像http://localhost:8080这样的字符串,并且我想提取url的不同部分,比如协议http、域名(本地主机)和端口(8080),那么在typescript中最好的方法是什么?
我可以对字符串进行简单的解析,以获得不同的值。但不确定这是否是最好的/最干净的方式。我是否应该首先将这个字符串转换为有效的URL (使用某个库),然后从其中获取主机名、协议和端口?Java会有这样的库,可以很容易地让我做到这一点,但是我如何用typescript实现同样的功能呢?
发布于 2017-05-05 03:19:44
您可以使用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并不是所有的浏览器都实现了它,但是如果你想使用它,你可以找到它的多边形填充。
编辑
在node中,您可以执行以下操作:
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如果你得到这个编译错误:
错误url:找不到模块‘TS2307’
然后,您需要节点定义:
npm install @types/node发布于 2017-05-05 04:57:28
您可以使用HTMLAnchorElement来实现此目的
let a = document.createElement("a");
a.href = "http://localhost:8080";
console.log(a.protocol);
console.log(a.host);
console.log(a.port);发布于 2017-05-06 00:40:09
如果使用的是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); // 8080https://stackoverflow.com/questions/43791067
复制相似问题