Skip to content

Commit ff1990c

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 f2279f8 commit ff1990c

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
@@ -1300,6 +1300,24 @@ url.resolve('http://example.com/', '/one'); // 'http://example.com/one'
13001300
url.resolve('http://example.com/one', '/two'); // 'http://example.com/two'
13011301
```
13021302

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+
13031321
<a id="whatwg-percent-encoding"></a>
13041322
## Percent-encoding in URLs
13051323

0 commit comments

Comments
 (0)