From ff1990c4094f88992287626f5cf343dfa2724c76 Mon Sep 17 00:00:00 2001 From: Antoine du Hamel Date: Wed, 24 Feb 2021 13:53:59 +0100 Subject: [PATCH] doc: add url.resolve replacement example Fixes: https://github.com/nodejs/node/issues/37492 PR-URL: https://github.com/nodejs/node/pull/37501 Reviewed-By: James M Snell Reviewed-By: Darshan Sen --- doc/api/url.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) 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