Skip to content

Commit 0fac27d

Browse files
aduh95targos
authored andcommitted
doc: add url.resolve replacement example
Fixes: #37492 PR-URL: #37501 Reviewed-By: James M Snell <jasnell@gmail.com> Reviewed-By: Darshan Sen <raisinten@gmail.com>
1 parent b1e188d commit 0fac27d

File tree

1 file changed

+18
-0
lines changed

1 file changed

+18
-0
lines changed

doc/api/url.md

+18
Original file line numberDiff line numberDiff line change
@@ -1362,6 +1362,24 @@ url.resolve('http://example.com/', '/one'); // 'http://example.com/one'
13621362
url.resolve('http://example.com/one', '/two'); // 'http://example.com/two'
13631363
```
13641364

1365+
You can achieve the same result using the WHATWG URL API:
1366+
1367+
```js
1368+
function resolve(from, to) {
1369+
const resolvedUrl = new URL(to, new URL(from, 'resolve://'));
1370+
if (resolvedUrl.protocol === 'resolve:') {
1371+
// `from` is a relative URL.
1372+
const { pathname, search, hash } = resolvedUrl;
1373+
return pathname + search + hash;
1374+
}
1375+
return resolvedUrl.toString();
1376+
}
1377+
1378+
resolve('/one/two/three', 'four'); // '/one/two/four'
1379+
resolve('http://example.com/', '/one'); // 'http://example.com/one'
1380+
resolve('http://example.com/one', '/two'); // 'http://example.com/two'
1381+
```
1382+
13651383
<a id="whatwg-percent-encoding"></a>
13661384
## Percent-encoding in URLs
13671385

0 commit comments

Comments
 (0)