Skip to content

Commit

Permalink
doc: add url.resolve replacement example
Browse files Browse the repository at this point in the history
  • Loading branch information
aduh95 committed Feb 24, 2021
1 parent 76a073b commit 5bddf51
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 5bddf51

Please sign in to comment.