如果我有一个类似 http://localhost:8080 的字符串 我想提取 url 的不同部分,例如协议(protocol) http、域名 (localhost) 和端口 (8080),在 typescript 中最好的方法是什么?
我可以对字符串进行简单的解析来获取不同的值。但不确定这是否是最好/最干净的方法。我是否应该首先将此字符串转换为有效的 URL(使用某些库),然后从中获取主机名、协议(protocol)和端口? Java 会有这样的库,可以很容易地让我做到这一点,但我如何使用 typescript 实现同样的目标?
最佳答案
您可以使用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
它并未在所有浏览器中实现,但如果您想使用它,您可以找到它的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
如果您收到此编译错误:
error TS2307: Cannot find module 'url'
然后您需要节点定义:
npm install @types/node
关于javascript - typescript 从包含 url 的字符串中获取主机名、协议(protocol)、端口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43791067/