GeezerVison is showing github.com — doc: add url.resolve replacement example · nodejs/node@ff1990c
File tree
Expand file treeCollapse file tree
Open diff view settings
Expand file treeCollapse file tree
Open diff view settings
Collapse file
Copy file name to clipboardExpand all lines: doc/api/url.md +18Lines changed: 18 additions & 0 deletions - Display the source diff
- Display the rich diff
| Original file line number | Diff line number | Diff line change |
|---|
@@ -1300,6 +1300,24 @@ url.resolve('http://example.com/', '/one'); // 'http://example.com/one' |
1300 | 1300 | url.resolve('http://example.com/one', '/two'); // 'http://example.com/two' |
1301 | 1301 | ``` |
1302 | 1302 |
|
| 1303 | +You can achieve the same result using the WHATWG URL API: |
| 1304 | + |
| 1305 | +```js |
| 1306 | +function resolve(from, to) { |
| 1307 | + const resolvedUrl = new URL(to, new URL(from, 'resolve://')); |
| 1308 | + if (resolvedUrl.protocol === 'resolve:') { |
| 1309 | + // `from` is a relative URL. |
| 1310 | + const { pathname, search, hash } = resolvedUrl; |
| 1311 | + return pathname + search + hash; |
| 1312 | + } |
| 1313 | + return resolvedUrl.toString(); |
| 1314 | +} |
| 1315 | + |
| 1316 | +resolve('/one/two/three', 'four'); // '/one/two/four' |
| 1317 | +resolve('http://example.com/', '/one'); // 'http://example.com/one' |
| 1318 | +resolve('http://example.com/one', '/two'); // 'http://example.com/two' |
| 1319 | +``` |
| 1320 | + |
1303 | 1321 | <a id="whatwg-percent-encoding"></a> |
1304 | 1322 | ## Percent-encoding in URLs |
1305 | 1323 |
|
|