diff --git a/doc/api/url.md b/doc/api/url.md index ad6455f2a1f545..f70f65c3c93721 100644 --- a/doc/api/url.md +++ b/doc/api/url.md @@ -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 baseUrl = new URL(from, 'resolve://'); + if(baseUrl.protocol !== 'resolve:') { + // `from` is an absolute URL. + return new URL(to, from).toString(); + } + const { pathname, search, hash } = new URL(to, baseUrl); + return pathname + search + hash; +} + +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' +``` + ## Percent-encoding in URLs