Skip to content

Commit

Permalink
doc: add url.resolve replacement example
Browse files Browse the repository at this point in the history
Fixes: #37492

PR-URL: #37501
Reviewed-By: James M Snell <[email protected]>
Reviewed-By: Darshan Sen <[email protected]>
  • Loading branch information
aduh95 authored and targos committed Feb 28, 2021
1 parent b1e188d commit 0fac27d
Showing 1 changed file with 18 additions and 0 deletions.
18 changes: 18 additions & 0 deletions doc/api/url.md
Original file line number Diff line number Diff line change
Expand Up @@ -1362,6 +1362,24 @@ url.resolve('http://example.com/', '/one'); // 'http://example.com/one'
url.resolve('http://example.com/one', '/two'); // 'http://example.com/two'
```

You can achieve the same result using the WHATWG URL API:

```js
function resolve(from, to) {
const resolvedUrl = new URL(to, new URL(from, 'resolve://'));
if (resolvedUrl.protocol === 'resolve:') {
// `from` is a relative URL.
const { pathname, search, hash } = resolvedUrl;
return pathname + search + hash;
}
return resolvedUrl.toString();
}

resolve('/one/two/three', 'four'); // '/one/two/four'
resolve('http://example.com/', '/one'); // 'http://example.com/one'
resolve('http://example.com/one', '/two'); // 'http://example.com/two'
```

<a id="whatwg-percent-encoding"></a>
## Percent-encoding in URLs

Expand Down

0 comments on commit 0fac27d

Please sign in to comment.