diff --git a/doc/api/url.md b/doc/api/url.md index 1fb73f0d3e10c7..c3ff62d98f36d0 100644 --- a/doc/api/url.md +++ b/doc/api/url.md @@ -1300,6 +1300,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' +``` + ## Percent-encoding in URLs