use*_*775 2 javascript url typescript
如果我有一个像http://localhost:8080这样的字符串 并且我想提取 url 的不同部分,比如协议 http、域名 (localhost) 和端口 (8080),那么最好的方法是什么打字稿?
我可以对字符串进行简单的解析以获得不同的值。但不确定这是否是最好/最干净的方法。我应该首先将此字符串转换为有效的 URL(使用某个库),然后从中获取主机名、协议和端口吗?Java 会有这样的库,可以让我很容易地做到这一点,但是我如何使用 typescript 实现相同的目标?
您可以使用URL 类:
let url = new URL("http://localhost:8080");
console.log(url.protocol); // http:
console.log(url.host); // localhost:8080
console.log(url.port); // 8080
Run Code Online (Sandbox Code Playgroud)
(操场上的代码)
它并未在所有浏览器中实现,但如果你想使用它,你可以找到它的 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
Run Code Online (Sandbox Code Playgroud)
如果您收到此编译错误:
错误 TS2307:找不到模块“url”
然后你需要节点定义:
npm install @types/node
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7913 次 |
| 最近记录: |